Пример #1
0
 void MessageView_Loaded(object sender, RoutedEventArgs e)
 {
     _messageViewModel = (MessageViewModel)this.DataContext;
     _messageViewModel.PropertyChanged += _messageViewModel_PropertyChanged;
     UpdateButtons();
     UpdateIcon();
 }
Пример #2
0
        public MainViewModel()
        {
            data = new DataAccess.Data();
            game = new Game(data, new List<string> { "Jessica", "Jack", "John", "Jane" }, Difficulty.Introductory);
            notifier = new Notifier();

            actionCardManager = game.ActionCardManager;
            actionManager = game.ActionManager;
            drawManager = game.DrawManager;
            infectionManager = game.InfectionManager;

            currentPlayer = new ObjectContext<Player>();
            currentPlayer.Context = game.CurrentPlayer;

            selectedPlayer = new ObjectContext<Player>();

            messageContext = new ObjectContext<StringBuilder>();
            messageContext.Context = new StringBuilder();

            BoardViewModel = new BoardViewModel(game, currentPlayer, selectedPlayer, notifier);
            MessageViewModel = new MessageViewModel(messageContext, game.NodeCounters);

            foreach (Player player in game.Players)
            {
                player.Hand.DiscardManager.Block += DiscardManagerBlock;
                player.Hand.DiscardManager.Release += DiscardManagerRelease;
            }

            drawManager.EpidemicDrawn += EpidemicDrawn;

            game.GameOver += Game_GameOver;
            game.GameWon += Game_GameWon;
        }
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, MessageViewModel comment)
        {
            if (comment != null)
            {
                var messageFromDb = this.messages.GetById(comment.Id);
                this.messages.Remove(messageFromDb);
            }

            return this.Json(new[] { comment }.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
Пример #4
0
        public void SendMessage(MessageViewModel message)
        {
            var user = data.Users.GetById(message.ToUserId);
            if (message.ToUserId != null && user != null)
            {
                message.CreatedOn = DateTime.Now;

                var messageToSave = Mapper.Map<Message>(message);
                var notification = new Notification
                {
                    UserId = message.ToUserId,
                    ForwardUrl = string.Format(GlobalPatternConstants.FORWARD_MESSAGE_URL, message.FromUserId),
                    Text = string.Format(GlobalPatternConstants.NOTIFICATION_NEW_MESSAGE,
                        message.FromUserName.TruncateLongString(GlobalConstants.TRUNCATE_SIZE))
                };
                var isSeen = false;

                if (ConnectedUsers.ContainsKey(message.ToUserId))
                {
                    messageToSave.IsSeen = true;
                    message.IsSeen = true;
                    notification.IsSeen = true;
                    isSeen = true;
                    var toUserId = ConnectedUsers[message.ToUserId];
                    Clients.Client(toUserId).AddMessage(message);
                }

                data.Notifications.Add(notification);
                data.Messages.Add(messageToSave);
                data.SaveChanges();

                var historyMessage = new MessageViewModel
                {
                    FromUserId = message.ToUserId,
                    FromUserName = message.ToUserName,
                    Text = message.Text,
                    IsSeen = messageToSave.IsSeen,
                    ToUserId = message.FromUserId,
                    ToUserName = message.FromUserName,
                    CreatedOn = message.CreatedOn
                };

                Clients.Client(Context.ConnectionId).AddToHistory(historyMessage);
                Clients.Client(Context.ConnectionId).ShowMessage(message);

                if(!isSeen)
                {
                     this.SendNotification(notification);
                }
            }
            else
            {
                Clients.Client(Context.ConnectionId).ShowError();
            }
        }
 public int AddData(JobTitleViewModel viewModel)
 {
     viewModel.JobTitle.RecCreatedDt = DateTime.Now;
     viewModel.JobTitle.RecCreatedBy = User.Identity.Name;
     var jobToSave = viewModel.JobTitle.CreateFrom();
     if (JobTitleService.AddJob(jobToSave))
     {
         TempData["message"] = new MessageViewModel { Message = "Employee has been Added", IsSaved = true };
         return 1;
     }
     return 0;
 }
Пример #6
0
        public void AddMessage(MessageViewModel viewModel)
        {
            try {
                Logger.DebugFormat ("Add Message {0}", viewModel);

                ControllerService.AddMessage (viewModel);
                Messages.Add (viewModel.Message);
            } catch (Exception ex) {
                Logger.ErrorFormat (ex, "Exception when adding message {0}", viewModel);
                throw;
            }
        }
Пример #7
0
		nfloat CalculateHeightFor(MessageViewModel msg, UITableView tableView)
		{
            var index = msg.IsIncoming ? 0 : 1;
			BubbleCell cell = sizingCells [index];
			if (cell == null)
				cell = sizingCells [index] = (BubbleCell)tableView.DequeueReusableCell (GetReuseId(msg));

			cell.ApplyCurrentTheme ();
			cell.Message = msg; 

			cell.SetNeedsLayout ();
			cell.LayoutIfNeeded ();
			CGSize size = cell.ContentView.SystemLayoutSizeFittingSize (UIView.UILayoutFittingCompressedSize);
			return NMath.Ceiling (size.Height) + 1;
		}
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, MessageViewModel message)
        {
            if (message != null && this.ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(message.Content))
                {
                    this.ModelState.AddModelError("Content", "Съдържанието на съобщението е задължително.");
                }

                var newMesage = new Message() { Content = message.Content };
                this.messages.Add(newMesage);
            }

            return this.Json(new[] { message }.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
Пример #9
0
        public async Task<ActionResult> SendMessage(MessageViewModel model)
        {
            if (ModelState.IsValid)
            {
                var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
                var message = new MailMessage();
                message.To.Add(new MailAddress("*****@*****.**"));
                message.Subject = "Board Games Kingdom";
                message.Body = string.Format(body, model.Name, model.Email, model.Message);
                message.IsBodyHtml = true;

                using (var smtp = new SmtpClient())
                {
                    await smtp.SendMailAsync(message);
                    return Json("Message sent");
                }
            }

            return Json("Could not send message");
        }
Пример #10
0
		private string GetMessageStatus(MessageViewModel message)
		{
			string msgStatus = "";
			switch (message.Status)
			{
			case MessageStatus.Unsent:
				msgStatus = "Sending";
				break;
			case MessageStatus.Sent:
				msgStatus = "Sent";
				break;
			case MessageStatus.Delivered:
				msgStatus = "Delivered";
				break;
			case MessageStatus.Seen:
				msgStatus = "Seen";
				break;
			}

			return msgStatus;
		}
        public ActionResult Create(MessageViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var taskName = model.Message;

                    var actor = SystemActors.TodoCoordinator;

                    actor.Tell(new Message(taskName,Guid.NewGuid()));
                    var routees = actor.Ask<Routees>(new GetRoutees());
                    var hasRoutees = routees.Result.Members.Any();
                    //Console.WriteLine("has routees" + routees.Result.Members.Any());
                }

                return RedirectToAction("Index", "Home");
            }
            catch (System.Exception ex)
            {
                return View();
            }
        }
 private void btnMessages_Click(object sender, RoutedEventArgs e)
 {
     DataContext = new MessageViewModel();
 }
Пример #13
0
 public void UpdateMessageContentOpened(MessageViewModel message)
 {
 }
 public VideoContent(MessageViewModel message)
 {
     InitializeComponent();
     UpdateMessage(message);
 }
        public ActionResult AddEdit(EmployeeViewModel viewModel)
        {
            var filePath = Server.MapPath(ConfigurationManager.AppSettings["EmployeeImage"] + User.Identity.Name + "/");
            if (ModelState.IsValid)
            {
                try
                {
                    //Create Folder for the current user/sponsor
                    if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
                    //Save image to Folder if Posting to Fb
                    if (viewModel.Employee.UploadImage != null)
                    {
                        var fileOldName = (viewModel.Employee.UploadImage.FileName);
                        //Rename Image file with time stamp
                        var filename = (DateTime.Now.ToString().Replace(".", "") + fileOldName).Replace("/", "").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("+", "");

                        viewModel.Employee.EmployeeImagePath = filename;
                        var savedFileName = Path.Combine(filePath, filename);
                        viewModel.Employee.UploadImage.SaveAs(savedFileName);
                    }
                    #region Update

                    if (viewModel.Employee.EmployeeId > 0)
                    {
                        viewModel.Employee.RecLastUpdatedDt = DateTime.Now;
                        viewModel.Employee.RecLastUpdatedBy = User.Identity.GetUserId();
                        var employeeToUpdate = viewModel.Employee.CreateFrom();
                        if (oEmployeeService.UpdateEmployee(employeeToUpdate))
                        {
                            TempData["message"] = new MessageViewModel { Message = "Employee has been Updated", IsUpdated = true };
                            return RedirectToAction("EmployeeLV");
                        }
                    }
                    #endregion

                    #region Add

                    else
                    {
                        viewModel.Employee.RecCreatedDt = DateTime.Now;
                        viewModel.Employee.RecCreatedBy = User.Identity.GetUserId();
                        var employeeToSave = viewModel.Employee.CreateFrom();

                        if (oEmployeeService.AddEmployee(employeeToSave))
                        {
                            TempData["message"] = new MessageViewModel { Message = "Employee has been Added", IsSaved = true };
                            viewModel.Employee.EmployeeId = employeeToSave.EmployeeId;
                            return RedirectToAction("EmployeeLV");
                        }
                    }

                    #endregion

                }
                catch (Exception e)
                {
                    return View(viewModel);
                }
            }

            return View(viewModel);
        }
        private async void SendCommandExecute()
        {
            if (string.IsNullOrWhiteSpace(NewMessageText)) return;

            NotifyPausedTyping();

            bool isMessageSent = privateChatManager.SendMessage(NewMessageText);

            if (!isMessageSent)
            {
                var messageService = ServiceLocator.Locator.Get<IMessageService>();
                await messageService.ShowAsync("Message", "Failed to send a message");
                return;
            }

            var messageViewModel = new MessageViewModel()
            {
                MessageText = NewMessageText,
                MessageType = MessageType.Outgoing,
                DateTime = DateTime.Now
            };

            await MessageCollectionViewModel.AddNewMessage(messageViewModel);
            var dialogsManager = ServiceLocator.Locator.Get<IDialogsManager>();
            await dialogsManager.UpdateDialogLastMessage(dialog.Id, NewMessageText, DateTime.Now);

            NewMessageText = "";
        }
 public async Task AddNewMessage(MessageViewModel messageViewModel)
 {
     await AddMessage(messageViewModel);
 }
 private async Task AddMessage(MessageViewModel messageViewModel)
 {
     if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
     {
         await AddMessageWithoutThreadAccessCheck(messageViewModel);
     }
     else
     {
         CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
         {
             await AddMessageWithoutThreadAccessCheck(messageViewModel);
         });
     }
 }
Пример #19
0
 public void UpdateMessageEdited(MessageViewModel message)
 {
     Footer.UpdateMessageEdited(message);
     Markup.Update(message, message.ReplyMarkup);
 }
Пример #20
0
 private void ViaBot_Click(MessageViewModel message)
 {
     message.Delegate.OpenViaBot(message.ViaBotUserId);
 }
Пример #21
0
        private void UpdateMessageHeader(MessageViewModel message)
        {
            MaybeUseInner(ref message);

            var paragraph = HeaderLabel;
            var admin     = AdminLabel;
            var parent    = Header;

            paragraph.Inlines.Clear();

            if (message == null)
            {
                return;
            }

            var chat = message.GetChat();

            var sticker = message.Content is MessageSticker;
            var light   = sticker || message.Content is MessageVideoNote;
            var shown   = false;

            if (!light && message.IsFirst && !message.IsOutgoing && !message.IsChannelPost && (chat.Type is ChatTypeBasicGroup || chat.Type is ChatTypeSupergroup))
            {
                var sender = message.GetSenderUser();

                var hyperlink = new Hyperlink();
                hyperlink.Inlines.Add(new Run {
                    Text = sender?.GetFullName()
                });
                hyperlink.UnderlineStyle = UnderlineStyle.None;
                hyperlink.Foreground     = PlaceholderHelper.GetBrush(message.SenderUserId);
                hyperlink.Click         += (s, args) => From_Click(message);

                paragraph.Inlines.Add(hyperlink);
                shown = true;
            }
            else if (!light && message.IsChannelPost && chat.Type is ChatTypeSupergroup)
            {
                var hyperlink = new Hyperlink();
                hyperlink.Inlines.Add(new Run {
                    Text = message.ProtoService.GetTitle(chat)
                });
                hyperlink.UnderlineStyle = UnderlineStyle.None;
                //hyperlink.Foreground = Convert.Bubble(message.ChatId);
                hyperlink.Click += (s, args) => From_Click(message);

                paragraph.Inlines.Add(hyperlink);
                shown = true;
            }
            else if (!light && message.IsFirst && message.IsSaved())
            {
                var title = string.Empty;
                if (message.ForwardInfo is MessageForwardedFromUser fromUser)
                {
                    title = message.ProtoService.GetUser(fromUser.SenderUserId)?.GetFullName();
                }
                else if (message.ForwardInfo is MessageForwardedPost post)
                {
                    title = message.ProtoService.GetTitle(message.ProtoService.GetChat(post.ForwardedFromChatId));
                }

                var hyperlink = new Hyperlink();
                hyperlink.Inlines.Add(new Run {
                    Text = title ?? string.Empty
                });
                hyperlink.UnderlineStyle = UnderlineStyle.None;
                //hyperlink.Foreground = Convert.Bubble(message.FwdFrom?.FromId ?? message.FwdFrom?.ChannelId ?? 0);
                hyperlink.Click += (s, args) => FwdFrom_Click(message);

                paragraph.Inlines.Add(hyperlink);
                shown = true;
            }

            if (shown)
            {
                if (admin != null && !message.IsOutgoing && message.Delegate != null && message.Delegate.IsAdmin(message.SenderUserId))
                {
                    paragraph.Inlines.Add(new Run {
                        Text = " " + Strings.Resources.ChatAdmin, Foreground = null
                    });
                }
            }

            var forward = false;

            if (message.ForwardInfo != null && !sticker && !message.IsSaved())
            {
                if (paragraph.Inlines.Count > 0)
                {
                    paragraph.Inlines.Add(new LineBreak());
                }

                paragraph.Inlines.Add(new Run {
                    Text = Strings.Resources.ForwardedMessage, FontWeight = FontWeights.Normal
                });
                paragraph.Inlines.Add(new LineBreak());
                paragraph.Inlines.Add(new Run {
                    Text = Strings.Resources.From + " ", FontWeight = FontWeights.Normal
                });

                var title = string.Empty;
                if (message.ForwardInfo is MessageForwardedFromUser fromUser)
                {
                    title = message.ProtoService.GetUser(fromUser.SenderUserId)?.GetFullName();
                }
                else if (message.ForwardInfo is MessageForwardedPost post)
                {
                    title = message.ProtoService.GetTitle(message.ProtoService.GetChat(post.ChatId));
                }

                var hyperlink = new Hyperlink();
                hyperlink.Inlines.Add(new Run {
                    Text = title
                });
                hyperlink.UnderlineStyle = UnderlineStyle.None;
                hyperlink.Foreground     = light ? new SolidColorBrush(Colors.White) : paragraph.Foreground;
                hyperlink.Click         += (s, args) => FwdFrom_Click(message);

                paragraph.Inlines.Add(hyperlink);
                forward = true;
            }

            //if (message.HasViaBotId && message.ViaBot != null && !message.ViaBot.IsDeleted && message.ViaBot.HasUsername)
            var viaBot = message.ProtoService.GetUser(message.ViaBotUserId);

            if (viaBot != null && viaBot.Type is UserTypeBot && !string.IsNullOrEmpty(viaBot.Username))
            {
                var hyperlink = new Hyperlink();
                hyperlink.Inlines.Add(new Run {
                    Text = (paragraph.Inlines.Count > 0 ? " via @" : "via @"), FontWeight = FontWeights.Normal
                });
                hyperlink.Inlines.Add(new Run {
                    Text = viaBot.Username
                });
                hyperlink.UnderlineStyle = UnderlineStyle.None;
                hyperlink.Foreground     = light ? new SolidColorBrush(Colors.White) : paragraph.Foreground;
                hyperlink.Click         += (s, args) => ViaBot_Click(message);

                if (paragraph.Inlines.Count > 0 && !forward)
                {
                    paragraph.Inlines.Insert(1, hyperlink);
                }
                else
                {
                    paragraph.Inlines.Add(hyperlink);
                }
            }

            if (paragraph.Inlines.Count > 0)
            {
                if (admin != null && shown && !message.IsOutgoing && message.Delegate != null && message.Delegate.IsAdmin(message.SenderUserId))
                {
                    admin.Visibility = Visibility.Visible;
                }
                else if (admin != null)
                {
                    admin.Visibility = Visibility.Collapsed;
                }

                paragraph.Inlines.Add(new Run {
                    Text = " "
                });
                paragraph.Visibility = Visibility.Visible;
                parent.Visibility    = Visibility.Visible;
            }
            else
            {
                if (admin != null)
                {
                    admin.Visibility = Visibility.Collapsed;
                }

                paragraph.Visibility = Visibility.Collapsed;
                parent.Visibility    = message.ReplyToMessageId != 0 ? Visibility.Visible : Visibility.Collapsed;
            }
        }
 public MessageRecord MapMessageViewModelToMessageRecord(MessageViewModel messageViewModel)
 {
     return(new MessageRecord(messageViewModel.RoomID, messageViewModel.AuthorName, messageViewModel.Text));
 }
Пример #23
0
 void MessageAdded(Message msg)
 {
     switch (msg.Command)
     {
         case ("PRIVMSG"): case("NOTICE"): case("JOIN"): case("PART"):
             var mvm = new MessageViewModel() { Content = msg.Trail, User = new User { Type = User.UserType.Normal, Name = msg.User }, Timestamp = DateTime.Now, Message = msg };
             if (!channels.ContainsKey(msg.Parameters[0])) channels.Add(msg.Parameters[0], new ChannelViewModel { Title = msg.Parameters[0] });
             App.Current.Dispatcher.BeginInvoke(new Action(() => channels[msg.Parameters[0]].Messages.Add(mvm)));
             break;
     }
 }
Пример #24
0
        public ActionResult ViewThread(int threadId)
        {
            var outModel = new MessageViewModel
            {
                Messages = _repository.SelectMessages(threadId)
            };

            return View(outModel);
        }
Пример #25
0
        public ActionResult CreateThread(MessageViewModel inModel)
        {
            if (!ModelState.IsValid)
            {
                return View(inModel);
            }

            var messageToCreate = new Message();
            if (inModel.ParentThreadId.HasValue)
            {
                messageToCreate.ParentThreadId = inModel.ParentThreadId;
            }

            if (inModel.ParentMessageId.HasValue)
            {
                messageToCreate.ParentMessageId = inModel.ParentMessageId;
            }

            messageToCreate.Recipient = inModel.Recipient;
            messageToCreate.Author = HttpContext.User.Identity.Name;
            messageToCreate.Subject = inModel.Subject;
            messageToCreate.Body = inModel.Body;
            messageToCreate.EntryDate = DateTime.Now;

            _repository.AddMessage(messageToCreate);

            return View("Success");
        }
Пример #26
0
        public AnimationContent(MessageViewModel message)
        {
            _message = message;

            DefaultStyleKey = typeof(AnimationContent);
        }
Пример #27
0
 public MainWindow()
 {
     InitializeComponent();
     DataContext = new MessageViewModel();
 }
Пример #28
0
 public void UpdateMessageViews(MessageViewModel message)
 {
     Footer.UpdateMessageViews(message);
 }
        private async Task GenerateProperNotificationMessages(MessageViewModel messageViewModel, Message originalMessage)
        {
            switch (originalMessage.NotificationType)
            {
                case NotificationTypes.FriendsRequest:
                    messageViewModel.MessageText = await BuildFriendsRequestMessage(originalMessage, messageViewModel.MessageType);
                    break;

                case NotificationTypes.FriendsAccept:
                    messageViewModel.MessageText = BuildFriendsAcceptMessage(messageViewModel.MessageType);
                    break;

                case NotificationTypes.FriendsReject:
                    messageViewModel.MessageText = BuildFriendsRejectMessage(messageViewModel.MessageType);
                    break;

                case NotificationTypes.FriendsRemove:
                    messageViewModel.MessageText = await BuildFriedsRemoveMessage(originalMessage, messageViewModel.MessageType);
                    break;

                case NotificationTypes.GroupCreate:
                    messageViewModel.MessageText = await BuildGroupCreateMessage(originalMessage);
                    break;

                case NotificationTypes.GroupUpdate:
                    messageViewModel.MessageText = await BuildGroupUpdateMessage(originalMessage);
                    break;
            }
        }
Пример #30
0
 public ActionResult Index(MessageViewModel view)
 {
     return(View());
 }
        public ActionResult PostRightsManagement(string roleValue, string selectedList)
        {

            RightsManagementViewModel viewModel = new RightsManagementViewModel();

            viewModel.Roles = userMenuRights.Roles.ToList();
            viewModel.Rights =
                userMenuRights.Menus.Select(
                    m =>
                        new Rights
                        {
                            MenuId = m.MenuId,
                            MenuTitle = m.MenuTitle,
                            IsParent = m.IsRootItem,
                            IsSelected = userMenuRights.MenuRights.Any(menu => menu.Menu.MenuId == m.MenuId),
                            ParentId = m.ParentItem != null ? m.ParentItem.MenuId : (int?)null
                        }).ToList();
            viewModel.SelectedRoleId = roleValue;
            TempData["message"] = new MessageViewModel
            {
                Message = "Record has been updated.",
                IsUpdated = true
           };
            return RedirectToAction("RightsManagement");
        }
Пример #32
0
 public Task <Message> UpdateMessage(int id, MessageViewModel model)
 {
     throw new NotImplementedException();
 }
Пример #33
0
        private void OnMessageReceived(object sender, MessageEventArgs e)
        {
            MessageViewModel message = new MessageViewModel(e.Message);

            Invoke((MethodInvoker)(() =>
                                        {
                                            _messages.Add(message);

                                            if (Settings.Default.MaxMessages > 0)
                                            {
                                                while (_messages.Count > Settings.Default.MaxMessages)
                                                {
                                                    _messages.RemoveAt(0);
                                                }
                                            }

                                            if (Settings.Default.AutoViewNewMessages ||
                                                Settings.Default.AutoInspectNewMessages)
                                            {
                                                if (Settings.Default.AutoViewNewMessages)
                                                {
                                                    ViewMessage(message);
                                                }

                                                if (Settings.Default.AutoInspectNewMessages)
                                                {
                                                    InspectMessage(message);
                                                }
                                            }
                                            else if (!Visible && Settings.Default.BalloonNotifications)
                                            {
                                                string body =
                                                    string.Format(
                                                        "From: {0}\nTo: {1}\nSubject: {2}\n<Click here to view more details>",
                                                        message.From,
                                                        message.To,
                                                        message.Subject);

                                                trayIcon.ShowBalloonTip(3000, "Message Recieved", body, ToolTipIcon.Info);
                                            }

                                            if (Visible && Settings.Default.BringToFrontOnNewMessage)
                                            {
                                                BringToFront();
                                                Activate();
                                            }
                                        }));
        }
Пример #34
0
        protected override async Task OnInitializedAsync()
        {
            try
            {
                string baseUrl = NavigationManager.BaseUri;

                _hubUrl = baseUrl.TrimEnd('/') + "/chatHub";


                hubConnection = new HubConnectionBuilder()
                                .WithUrl(_hubUrl, options =>
                {
                    options.AccessTokenProvider = async() =>
                    {
                        var accessTokenResult = await AccessTokenProvider.GetAuthenticationStateAsync();

                        return(await storage.GetTokenAsync());
                    };
                })
                                .Build();

                hubConnection.On <MessageViewModel>("newMessage", async(message) =>
                {
                    messages.Insert(0, message);
                    StateHasChanged();
                });
                hubConnection.On <string>("onError", async(message) =>
                {
                    MessageViewModel msg = new MessageViewModel();
                    msg.Content          = message;

                    messages.Insert(0, msg);
                    StateHasChanged();
                });
                hubConnection.On <UserViewModel>("joinedRoom", async(message) =>
                {
                    inputModel.CurrentRoom = message.CurrentRoom;
                    messages.Clear();
                    IList <MessageViewModel> mess = await hubConnection.InvokeAsync <IList <MessageViewModel> >("GetMessageHistory", inputModel.Room);
                    foreach (var m in mess)
                    {
                        messages.Insert(0, m);
                    }
                    StateHasChanged();
                });


                hubConnection.On <UserViewModel>("removeUser", async(message) =>
                {
                    users = await hubConnection.InvokeAsync <IList <UserViewModel> >("GetUsers", message.CurrentRoom);
                    StateHasChanged();
                });
                hubConnection.On <UserViewModel>("addUser", async(message) =>
                {
                    users = await hubConnection.InvokeAsync <IList <UserViewModel> >("GetUsers", message.CurrentRoom);
                    StateHasChanged();
                });
                hubConnection.On <RoomViewModel>("removeChatRoom", async(message) =>
                {
                    rooms = await hubConnection.InvokeAsync <IList <RoomViewModel> >("GetRooms");
                    StateHasChanged();
                });
                hubConnection.On <RoomViewModel>("addChatRoom", async(message) =>
                {
                    rooms = await hubConnection.InvokeAsync <IList <RoomViewModel> >("GetRooms");
                    StateHasChanged();
                });
                hubConnection.On <string>("onRoomDeleted", async(message) =>
                {
                    inputModel.Room      = "Lobby";
                    MessageViewModel msg = new MessageViewModel();
                    msg.Content          = $"Room was deleted, you are now moved back to {inputModel.Room}";

                    messages.Insert(0, msg);
                    await JoinRoom();
                    StateHasChanged();
                });


                await hubConnection.StartAsync();

                username = await hubConnection.InvokeAsync <string>("WhoAmI");

                inputModel.Room     = "Lobby";
                inputModel.Recipent = "Room";
                rooms = await hubConnection.InvokeAsync <IList <RoomViewModel> >("GetRooms");

                await JoinRoom();
            }
            catch (Exception ex)
            {
                MessageViewModel msg = new MessageViewModel();
                msg.Content = ex.Message;
                messages.Insert(0, msg);
            }
            finally
            {
                //  this.StateHasChanged();
            }
        }
Пример #35
0
        public ActionResult CreateThread()
        {
            var outmodel = new MessageViewModel();

            return View("Create", outmodel);
        }
        public void AddMessage(MessageViewModel messageViewModel)
        {
            var messagesCollection = GetMessagesCollection();

            messagesCollection.Save(messageViewModel);
        }
        public void UpdateFile(MessageViewModel message, File file)
        {
            var video = GetContent(message.Content);

            if (video == null)
            {
                return;
            }

            if (video.Thumbnail != null && video.Thumbnail.Photo.Id == file.Id)
            {
                UpdateThumbnail(message, file);
                return;
            }
            else if (video.VideoValue.Id != file.Id)
            {
                return;
            }

            var size = Math.Max(file.Size, file.ExpectedSize);

            if (file.Local.IsDownloadingActive)
            {
                Button.Glyph    = "\uE10A";
                Button.Progress = (double)file.Local.DownloadedSize / size;

                Subtitle.Text = string.Format("{0} / {1}", FileSizeConverter.Convert(file.Local.DownloadedSize, size), FileSizeConverter.Convert(size));
            }
            else if (file.Remote.IsUploadingActive || message.SendingState is MessageSendingStateFailed)
            {
                Button.Glyph    = "\uE10A";
                Button.Progress = (double)file.Remote.UploadedSize / size;

                Subtitle.Text = string.Format("{0} / {1}", FileSizeConverter.Convert(file.Remote.UploadedSize, size), FileSizeConverter.Convert(size));
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsDownloadingCompleted)
            {
                Button.Glyph    = "\uE118";
                Button.Progress = 0;

                Subtitle.Text = video.GetDuration() + ", " + FileSizeConverter.Convert(size);

                if (message.Delegate.CanBeDownloaded(message))
                {
                    _message.ProtoService.Send(new DownloadFile(file.Id, 32));
                }
            }
            else
            {
                if (message.IsSecret())
                {
                    Button.Glyph    = "\uE60D";
                    Button.Progress = 1;

                    Subtitle.Text = Locale.FormatTTLString(Math.Max(message.Ttl, video.Duration), true);
                }
                else
                {
                    Button.Glyph    = "\uE102";
                    Button.Progress = 1;

                    Subtitle.Text = video.GetDuration();
                }
            }
        }
Пример #38
0
        public ActionResult Send(string adAuthorId, int advertisementId, decimal price)
        {
            var advertisementAuthor = this.manager
                .Users
                .FirstOrDefault(u => u.Id == adAuthorId);

            if (advertisementAuthor == null)
            {
                throw new HttpException(404, "Author not found");
            }

            var advertisement = this.advertisements.GetById(advertisementId).FirstOrDefault();
            if (advertisement == null)
            {
                throw new HttpException(404, "Advertisement not found");
            }

            if (this.User.Identity.IsAuthenticated)
            {
                var currentUserId = this.User.Identity.GetUserId();
                if (adAuthorId == currentUserId)
                {
                    this.TempData["Error"] = "Не може да изпращате съобщения на себе си";

                    return this.RedirectToAction("Details", "Ads", new { id = advertisementId, area = "Advertisement" });
                }
            }

            var advertisementAuthorName = advertisementAuthor.FirstName + " " + advertisementAuthor.LastName;
            var viewModel = new MessageViewModel
            {
                AuthorName = advertisementAuthorName,
                AdvertisementAuthorId = adAuthorId,
                AdvertisementTitle = advertisement.Title
            };

            return this.View(viewModel);
        }
Пример #39
0
 public IActionResult Detail([FromForm] string[] fields, [FromForm] MessageViewModel model)
 {
     FIELDS = fields;
     return(RedirectToAction("Detail", model));
 }
Пример #40
0
        public ActionResult DetailView(int id)
        {
            var       userName                = User.Identity.GetUserName();
            DataTable dtblProject             = new DataTable();
            DataTable dtblMessageboard        = new DataTable();
            DataTable dtblMessageboardReplies = new DataTable();
            DataTable dtblProjectUser         = new DataTable();
            DataTable img = new DataTable();

            byte[] profileImage = null;
            string contentType  = "";

            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                string         query = "SELECT * FROM Projects WHERE Id = @Id";
                SqlDataAdapter sqlDa = new SqlDataAdapter(query, sqlCon);
                sqlDa.SelectCommand.Parameters.AddWithValue("@Id", id);
                sqlDa.Fill(dtblProject);

                query = "SELECT * FROM Messageboards WHERE ProjectId = @Id";
                sqlDa = new SqlDataAdapter(query, sqlCon);
                sqlDa.SelectCommand.Parameters.AddWithValue("@Id", id);
                sqlDa.Fill(dtblMessageboard);

                query = "SELECT * FROM ProjectUser WHERE ProjectId = @Id";
                sqlDa = new SqlDataAdapter(query, sqlCon);
                sqlDa.SelectCommand.Parameters.AddWithValue("@Id", id);
                sqlDa.Fill(dtblProjectUser);

                string selectQuery = "SELECT AspNetUsers.ProfileImage, AspNetUsers.FileContentType, AspNetUsers.UserName FROM AspNetUsers, ProjectUser WHERE ProjectUser.ProjectId = " + id + " AND AspNetUsers.UserName = ProjectUser.Name";

                // Read Byte [] Value from Sql Table
                SqlCommand selectCommand = new SqlCommand(selectQuery, sqlCon);

                sqlDa = new SqlDataAdapter(selectQuery, sqlCon);
                sqlDa.Fill(img);

/*
 *              SqlDataReader reader;
 *              reader = selectCommand.ExecuteReader();
 *              Dictionary<string, string> images = new Dictionary<string, string>();
 *              if (reader != null)
 *              {
 *                  if (reader.Read() && !System.Convert.IsDBNull(reader.GetValue(0)))
 *                  {
 *                      profileImage = (byte[])reader.GetValue(0);
 *                      contentType = Convert.ToString(reader.GetValue(1));
 *                      userName = Convert.ToString(reader.GetValue(2));
 *
 *                      images.Add("testo", "test");
 *
 *                      images.Add(userName, string.Format("data:{0};base64,{1}",
 *                          contentType, Convert.ToBase64String(profileImage)));
 *                      Debug.WriteLine(userName);
 *                      Debug.WriteLine("++++++++++++++++++ " + userName +" "+ string.Format("data:{0};base64,{1}",
 *                          contentType, Convert.ToBase64String(profileImage)));
 *
 *                  }
 *              }
 */
                //ViewBag.Images = images;
            }

            Dictionary <string, string> images = new Dictionary <string, string>();

            Debug.WriteLine("++++++++++++++++++ " + img.Rows.Count);
            images.Add("testo", "test");
            if (img.Rows.Count >= 1)
            {
                for (int i = 0; i < img.Rows.Count; i++)
                {
                    if (img.Rows[i][0] != System.DBNull.Value && img.Rows[i][1] != System.DBNull.Value && img.Rows[i][2] != System.DBNull.Value)
                    {
                        profileImage = (byte[])img.Rows[i][0];
                        contentType  = img.Rows[i][1].ToString();
                        userName     = img.Rows[i][2].ToString();

                        Debug.WriteLine("++++++++++++++++++ " + img.Rows.Count + " " + userName);

                        images.Add(userName, string.Format("data:{0};base64,{1}", contentType, Convert.ToBase64String(profileImage)));
                    }
                }
            }
            ViewBag.Images = images;

            if (dtblProject.Rows.Count == 1)
            {
                ProjectViewModel pvm = new ProjectViewModel();
                pvm.Id          = Convert.ToInt32(dtblProject.Rows[0][0].ToString());
                pvm.Name        = dtblProject.Rows[0][1].ToString();
                pvm.Description = dtblProject.Rows[0][2].ToString();
                pvm.ManagerId   = dtblProject.Rows[0][3].ToString();
                pvm.ManagerName = dtblProject.Rows[0][4].ToString();

                for (int i = 0; i < dtblProjectUser.Rows.Count; i++)
                {
                    pvm.Member.Add(dtblProjectUser.Rows[i][1].ToString());
                }
                for (int i = 0; i < dtblMessageboard.Rows.Count; i++)
                {
                    MessageViewModel mvm = new MessageViewModel();
                    mvm.Id              = Convert.ToInt32(dtblMessageboard.Rows[i][0].ToString());
                    mvm.Message         = dtblMessageboard.Rows[i][1].ToString();
                    mvm.Author          = dtblMessageboard.Rows[i][3].ToString();
                    mvm.Date            = dtblMessageboard.Rows[i][4].ToString();
                    mvm.FileName        = dtblMessageboard.Rows[i][5].ToString();
                    mvm.FileContentType = dtblMessageboard.Rows[i][6].ToString();
                    using (SqlConnection sqlCon = new SqlConnection(connectionString))
                    {
                        sqlCon.Open();
                        string         query = "SELECT * FROM MessageboardReplies WHERE MessageboardId = @mId";
                        SqlDataAdapter sqlDa = new SqlDataAdapter(query, sqlCon);
                        sqlDa.SelectCommand.Parameters.AddWithValue("@mId", dtblMessageboard.Rows[i][0].ToString());
                        sqlDa.Fill(dtblMessageboardReplies);
                    }
                    for (int j = 0; j < dtblMessageboardReplies.Rows.Count; j++)
                    {
                        string info1 = dtblMessageboardReplies.Rows[j][3].ToString();
                        string info2 = dtblMessageboard.Rows[i][0].ToString();
                        System.Diagnostics.Debug.WriteLine(info1 + " compared to: " + info2);
                        if (dtblMessageboardReplies.Rows[j][3].ToString() == dtblMessageboard.Rows[i][0].ToString())
                        {
                            MessageReplyModel mrm = new MessageReplyModel();
                            mrm.Id      = Convert.ToInt32(dtblMessageboardReplies.Rows[j][0]);
                            mrm.Message = dtblMessageboardReplies.Rows[j][1].ToString();
                            mrm.Author  = dtblMessageboardReplies.Rows[j][2].ToString();
                            mrm.Date    = dtblMessageboardReplies.Rows[j][4].ToString();
                            mvm.MessageReplies.Add(mrm);
                            System.Diagnostics.Debug.WriteLine(mvm.MessageReplies.Count.ToString());
                        }
                    }
                    pvm.Messages.Add(mvm);
                }

                ViewBag.IsAuthorized = userName;

                return(View(pvm));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Пример #41
0
        public void UpdateMessage(MessageViewModel message)
        {
            var recycled = _message?.Id == message.Id;

            _message = message;

            var poll = message.Content as MessagePoll;

            if (poll == null | !_templateApplied)
            {
                return;
            }

            var results = poll.Poll.IsClosed || poll.Poll.Options.Any(x => x.IsChosen);

            if (poll.Poll.Type is PollTypeQuiz && poll.Poll.CloseDate != 0 && !results)
            {
                var now = DateTime.Now.ToTimestamp();

                var diff = poll.Poll.CloseDate - now;
                if (diff > 0)
                {
                    TimeoutLabel.Visibility = Visibility.Visible;
                    Timeout.Text            = TimeSpan.FromSeconds(diff).ToString("m\\:ss");

                    if (_timeoutTimer == null)
                    {
                        _timeoutTimer          = new DispatcherTimer();
                        _timeoutTimer.Interval = TimeSpan.FromSeconds(1);
                        _timeoutTimer.Tick    += TimeoutTimer_Tick;
                    }

                    _timeoutTimer.Stop();
                    _timeoutTimer.Start();
                }
                else
                {
                    _timeoutTimer?.Stop();
                    TimeoutLabel.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                _timeoutTimer?.Stop();
                TimeoutLabel.Visibility = Visibility.Collapsed;
            }

            Question.Text = poll.Poll.Question;
            Votes.Text    = poll.Poll.TotalVoterCount > 0
                ? Locale.Declension(poll.Poll.Type is PollTypeQuiz ? "Answer" : "Vote", poll.Poll.TotalVoterCount)
                : poll.Poll.Type is PollTypeQuiz
                ? Strings.Resources.NoVotesQuiz
                : Strings.Resources.NoVotes;

            if (poll.Poll.Type is PollTypeRegular reg)
            {
                Type.Text              = poll.Poll.IsClosed ? Strings.Resources.FinalResults : poll.Poll.IsAnonymous ? Strings.Resources.AnonymousPoll : Strings.Resources.PublicPoll;
                View.Visibility        = results && poll.Poll.TotalVoterCount > 0 && !poll.Poll.IsAnonymous ? Visibility.Visible : Visibility.Collapsed;
                Submit.Visibility      = !results && reg.AllowMultipleAnswers ? Visibility.Visible : Visibility.Collapsed;
                Explanation.Visibility = Visibility.Collapsed;
            }
            else if (poll.Poll.Type is PollTypeQuiz quiz)
            {
                Type.Text              = poll.Poll.IsClosed ? Strings.Resources.FinalResults : poll.Poll.IsAnonymous ? Strings.Resources.AnonymousQuizPoll : Strings.Resources.QuizPoll;
                View.Visibility        = results && poll.Poll.TotalVoterCount > 0 && !poll.Poll.IsAnonymous ? Visibility.Visible : Visibility.Collapsed;
                Submit.Visibility      = Visibility.Collapsed;
                Explanation.Visibility = results && !string.IsNullOrEmpty(quiz.Explanation?.Text) ? Visibility.Visible : Visibility.Collapsed;
            }

            Votes.Visibility = View.Visibility == Visibility.Collapsed && Submit.Visibility == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed;

            Submit.IsEnabled = false;
            //Options.Children.Clear();

            //foreach (var option in poll.Poll.Options)
            //{
            //    var button = new PollOptionControl();
            //    button.Click += Option_Click;
            //    button.UpdatePollOption(poll.Poll, option);

            //    Options.Children.Add(button);
            //}

            for (int i = 0; i < Math.Max(poll.Poll.Options.Count, Options.Children.Count); i++)
            {
                if (i < Options.Children.Count)
                {
                    var button = Options.Children[i] as PollOptionControl;
                    button.Click     -= Option_Click;
                    button.Checked   -= Option_Toggled;
                    button.Unchecked -= Option_Toggled;

                    if (i < poll.Poll.Options.Count)
                    {
                        button.UpdatePollOption(poll.Poll, poll.Poll.Options[i]);

                        if (poll.Poll.Type is PollTypeRegular regular && regular.AllowMultipleAnswers)
                        {
                            button.Checked   += Option_Toggled;
                            button.Unchecked += Option_Toggled;
                        }
                        else
                        {
                            button.Click += Option_Click;
                        }
                    }
                    else
                    {
                        Options.Children.Remove(button);
                    }
                }
 public MessageWindowViewModel(MessageViewModel viewModel)
     : this(viewModel, BottomPanelButtons.Ok)
 { }
Пример #43
0
        private void UpdateFile(MessageViewModel message, File file)
        {
            var animation = GetContent(message.Content);

            if (animation == null || !_templateApplied)
            {
                return;
            }

            if (animation.AnimationValue.Id != file.Id)
            {
                return;
            }

            var size = Math.Max(file.Size, file.ExpectedSize);

            if (file.Local.IsDownloadingActive)
            {
                //Button.Glyph = Icons.Cancel;
                Button.SetGlyph(file.Id, MessageContentState.Downloading);
                Button.Progress = (double)file.Local.DownloadedSize / size;

                Subtitle.Text   = string.Format("{0} / {1}", FileSizeConverter.Convert(file.Local.DownloadedSize, size), FileSizeConverter.Convert(size));
                Overlay.Opacity = 1;

                Player.Source = null;
            }
            else if (file.Remote.IsUploadingActive || message.SendingState is MessageSendingStateFailed)
            {
                //Button.Glyph = Icons.Cancel;
                Button.SetGlyph(file.Id, MessageContentState.Uploading);
                Button.Progress = (double)file.Remote.UploadedSize / size;

                Subtitle.Text   = string.Format("{0} / {1}", FileSizeConverter.Convert(file.Remote.UploadedSize, size), FileSizeConverter.Convert(size));
                Overlay.Opacity = 1;

                Player.Source = null;
            }
            else if (file.Local.CanBeDownloaded && !file.Local.IsFileExisting())
            {
                //Button.Glyph = Icons.Download;
                Button.SetGlyph(file.Id, MessageContentState.Download);
                Button.Progress = 0;

                Subtitle.Text   = Strings.Resources.AttachGif + ", " + FileSizeConverter.Convert(size);
                Overlay.Opacity = 1;

                Player.Source = null;

                if (message.Delegate.CanBeDownloaded(animation, file))
                {
                    _message.ProtoService.DownloadFile(file.Id, 32);
                }
            }
            else
            {
                if (message.IsSecret())
                {
                    //Button.Glyph = Icons.Ttl;
                    Button.SetGlyph(file.Id, MessageContentState.Ttl);
                    Button.Progress = 1;

                    Subtitle.Text   = Locale.FormatTtl(Math.Max(message.Ttl, animation.Duration), true);
                    Overlay.Opacity = 1;

                    Player.Source = null;
                }
                else
                {
                    //Button.Glyph = Icons.Animation;
                    Button.SetGlyph(file.Id, MessageContentState.Animation);
                    Button.Progress = 1;

                    Subtitle.Text   = Strings.Resources.AttachGif;
                    Overlay.Opacity = 1;

                    Player.Source = new LocalVideoSource(file);
                    message.Delegate.ViewVisibleMessages(false);
                }
            }
        }
 public MessageWindowViewModel(MessageViewModel messageViewModel, BottomPanelButtons buttons)
 {
     _messageViewModel = messageViewModel;
     // "this" is passed as the BottomPanelViewModel's IHasBottomPanel parameter:
     _bottomPanelViewModel = new BottomPanelViewModel(buttons, this);
 }
 public AudioMessageContentViewModel(AudioMessage message, MessageViewModel parent)
     : base(message, parent)
 {
     this.PlayCommand  = new DefaultCommand(o => this.Play(), true);
     this.PauseCommand = new DefaultCommand(o => this.Pause(), false);
 }
Пример #46
0
        public DocumentContent(MessageViewModel message)
        {
            _message = message;

            DefaultStyleKey = typeof(DocumentContent);
        }
 private async Task AddMessageWithoutThreadAccessCheck(MessageViewModel messageViewModel)
 {
     var messageGroup = Messages.FirstOrDefault(msgGroup => msgGroup.Date.Date == messageViewModel.DateTime.Date);
     if (messageGroup == null)
     {
         messageGroup = new DayOfMessages { Date = messageViewModel.DateTime.Date };
         Messages.Add(messageGroup);
     }
     messageGroup.Add(messageViewModel);
 }
 public CalculationServerInfoJob(MessageViewModel e_mvm)
 {
     this.MessageViewModel_ = e_mvm;
 }
        private async Task<MessageViewModel> CreateMessageViewModelFromMessage(Message message)
        {
            var messageViewModel = new MessageViewModel
            {
                MessageText = message.MessageText,
                DateTime = message.DateSent.ToDateTime(),
                NotificationType = message.NotificationType,
                SenderId = message.SenderId
            };

            int currentUserId = SettingsManager.Instance.ReadFromSettings<int>(SettingsKeys.CurrentUserId);
            messageViewModel.MessageType = messageViewModel.SenderId == currentUserId ? MessageType.Outgoing : MessageType.Incoming;

            var cachingQbClient = ServiceLocator.Locator.Get<ICachingQuickbloxClient>();
            var senderUser = await cachingQbClient.GetUserById(message.SenderId);
            if (senderUser != null) messageViewModel.SenderName = senderUser.FullName;

            return messageViewModel;
        }
 public async Task<ActionResult> Create(RoleViewModel roleViewModel)
 {
     if (ModelState.IsValid)
     {
         var role = new AspNetRole();
         role.Name = roleViewModel.Name;
         int rolesCount = RoleManager.Roles.Count() + 1;
         role.Id = rolesCount.ToString();
         if (!RoleManager.RoleExists(role.Name))
         {
             var roleresult = await RoleManager.CreateAsync(role);
             if (!roleresult.Succeeded)
             {
                 TempData["message"] = new MessageViewModel
                 {
                     Message = "Error in creating role",
                     IsError = true
                 };
                 return View();
             }
             TempData["message"] = new MessageViewModel
             {
                 Message = "Role has been created successfully",
                 IsSaved = true
             };
         }
         return RedirectToAction("Index");
     }
     return View();
 }
Пример #51
0
        private void OnValueChanged(MessageViewModel newValue)
        {
            if (Indicator == null)
            {
                return;
            }

            if (newValue == null)
            {
                Visibility = Visibility.Collapsed;
                return;
            }
            else
            {
                Visibility = Visibility.Visible;
            }

            //var geoLiveMedia = newValue.Media as TLMessageMediaGeoLive;
            //if (geoLiveMedia == null)
            //{
            //    return;
            //}

            //var value = BindConvert.Current.DateTime(newValue.Date + geoLiveMedia.Period);
            //var difference = value - DateTime.Now;

            //_angleStoryboard.SkipToFill();

            //if (difference > TimeSpan.Zero)
            //{
            //    var angleAnimation = (DoubleAnimation)_angleStoryboard.Children[0];
            //    angleAnimation.From = 359 - (difference.TotalSeconds / geoLiveMedia.Period * 359);
            //    angleAnimation.To = 359;
            //    angleAnimation.Duration = difference;
            //    _angleStoryboard.Begin();
            //}

            //TimeoutLabel.Text = GetTimeout(difference);



            //double value;
            ////if (oldValue > 0.0 && oldValue < 1.0 && newValue == 0.0)
            ////{
            ////    value = 359.0;
            ////}
            ////else
            //{
            //    value = newValue * 359.0;
            //    if (value < 0.0)
            //    {
            //        value = 0.0;
            //    }
            //    else if (value > 359.0)
            //    {
            //        value = 359.0;
            //    }
            //}
            //if (value != Indicator.StartAngle)
            //{
            //    if (value > 0.0 && value < 359.0)
            //    {
            //        Visibility = Windows.UI.Xaml.Visibility.Visible;
            //    }

            //    if (value > Indicator.StartAngle)
            //    {
            //        _angleStoryboard.SkipToFill();

            //        var angleAnimation = (DoubleAnimation)_angleStoryboard.Children[0];
            //        angleAnimation.To = value;
            //        angleAnimation.Duration = DueTime - DateTime.Now;
            //        _angleStoryboard.Begin();
            //    }
            //}
        }
Пример #52
0
        public async Task <IActionResult> Post([FromBody] MessageViewModel message)
        {
            await _messageService.PostAsync(message);

            return(Ok());
        }
Пример #53
0
        //TODO: use RecycleView
        private void OnMessageViewCreate(int position, View view, MessageViewModel msgVm)
        {
            var textVm = msgVm as TextMessageViewModel;
            var imageVm = msgVm as ImageMessageViewModel;

            var msgDate = view.FindViewById<TextView>(Resource.Id.msg_timestamp);
            msgDate.Text = new TimestampConverter().Convert(msgVm.Timestamp);

            if (!msgVm.IsIncoming)
            {
                var msgStatus = view.FindViewById<ImageView>(Resource.Id.msg_status);
                switch (msgVm.Status)
                {
                    case MessageStatus.Unsent:
                        msgStatus.SetImageResource(Resource.Drawable.msg_status_sending);
                        break;
                    case MessageStatus.Sent:
                        msgStatus.SetImageResource(Resource.Drawable.msg_status_sent);
                        break;
                    case MessageStatus.Delivered:
                        msgStatus.SetImageResource(Resource.Drawable.msg_status_delivered);
                        break;
                    case MessageStatus.Seen:
                        msgStatus.SetImageResource(Resource.Drawable.msg_status_seen);
                        break;
                }
            }

            if (imageVm != null)
            {
                var thumbnailView = view.FindViewById<ImageView>(Resource.Id.thumnail_image);
                thumbnailView.SetImageBitmap(BitmapFactory.DecodeByteArray(imageVm.Thumbnail, 0, imageVm.Thumbnail.Length));
            }
            else if (textVm != null)
            {
                var msgText = view.FindViewById<TextView>(Resource.Id.msg_text);
                msgText.Text = textVm.Text;
            }

			var msgImage = view.FindViewById<ImageView> (Resource.Id.msg_photo);

			var photoUrl = string.Empty;
            if (msgVm.IsIncoming)
                photoUrl = viewModel.Friend.Photo;
            else
                photoUrl = EndPoints.BaseUrl + Settings.Avatar;
			
			UrlImageViewHelper.SetUrlDrawable (msgImage, photoUrl, Resource.Drawable.default_photo);
        }
Пример #54
0
        public async void PlayMessage(MessageViewModel message, FrameworkElement target)
        {
            var text = message.Content as MessageText;

            // If autoplay is enabled and the message contains a video note, then we want a different behavior
            if (ViewModel.Settings.IsAutoPlayAnimationsEnabled && (message.Content is MessageVideoNote || text?.WebPage != null && text.WebPage.Video != null))
            {
                ViewModel.PlaybackService.Enqueue(message.Get());
                //if (_old.TryGetValue(message.Id, out MediaPlayerItem item))
                //{
                //    if (item.Presenter == null || item.Presenter.MediaPlayer == null)
                //    {
                //        return;
                //    }

                //    // If the video player is muted, then let's play the video again with audio turned on
                //    if (item.Presenter.MediaPlayer.IsMuted)
                //    {
                //        TypedEventHandler<MediaPlayer, object> handler = null;
                //        handler = (player, args) =>
                //        {
                //            player.MediaEnded -= handler;
                //            player.IsMuted = true;
                //            player.IsLoopingEnabled = true;
                //            player.Play();
                //        };

                //        item.Presenter.MediaPlayer.MediaEnded += handler;
                //        item.Presenter.MediaPlayer.IsMuted = false;
                //        item.Presenter.MediaPlayer.IsLoopingEnabled = false;
                //        item.Presenter.MediaPlayer.PlaybackSession.Position = TimeSpan.Zero;

                //        // Mark it as viewed if needed
                //        if (message.Content is MessageVideoNote videoNote && !message.IsOutgoing && !videoNote.IsViewed)
                //        {
                //            ViewModel.ProtoService.Send(new OpenMessageContent(message.ChatId, message.Id));
                //        }
                //    }
                //    // If the video player is paused, then resume playback
                //    else if (item.Presenter.MediaPlayer.PlaybackSession.PlaybackState == MediaPlaybackState.Paused)
                //    {
                //        item.Presenter.MediaPlayer.Play();
                //    }
                //    // And last, if the video player can be pause, then pause it
                //    else if (item.Presenter.MediaPlayer.PlaybackSession.CanPause)
                //    {
                //        item.Presenter.MediaPlayer.Pause();
                //    }
                //}
            }
            else if (ViewModel.Settings.IsAutoPlayAnimationsEnabled && (message.Content is MessageAnimation || (text?.WebPage != null && text.WebPage.Animation != null) || (message.Content is MessageGame game && game.Game.Animation != null)))
            {
                if (_old.TryGetValue(message.AnimationHash(), out MediaPlayerItem item))
                {
                    GalleryViewModelBase viewModel;
                    if (message.Content is MessageAnimation)
                    {
                        viewModel = new ChatGalleryViewModel(ViewModel.ProtoService, ViewModel.Aggregator, message.ChatId, ViewModel.ThreadId, message.Get());
                    }
                    else
                    {
                        viewModel = new SingleGalleryViewModel(ViewModel.ProtoService, ViewModel.Aggregator, new GalleryMessage(ViewModel.ProtoService, message.Get()));
                    }

                    await GalleryView.GetForCurrentView().ShowAsync(viewModel, () => target);
                }
                else
                {
                    ViewVisibleMessages(false);
                }
            }
Пример #55
0
        private void InspectMessage(MessageViewModel message)
        {
            message.MarkAsViewed();

            InspectorWindow form = new InspectorWindow(message.Parts);
            form.Show();

            messageGrid.Refresh();
        }
Пример #56
0
 NSString GetReuseId(MessageViewModel message)
 {
     return(message.IsIncoming ? IncomingCell.CellId : OutgoingCell.CellId);
 }
Пример #57
0
        private void ViewMessage(MessageViewModel message)
        {
            TempFileCollection tempFiles = new TempFileCollection();
            FileInfo msgFile = new FileInfo(tempFiles.AddExtension("eml"));
            message.SaveToFile(msgFile);

            if (Registry.ClassesRoot.OpenSubKey(".eml", false) == null || string.IsNullOrEmpty((string)Registry.ClassesRoot.OpenSubKey(".eml", false).GetValue(null)))
            {
                switch (MessageBox.Show(this,
                                        "You don't appear to have a viewer application associated with .eml files!\nWould you like to download Windows Live Mail (free from live.com website)?",
                                        "View Message", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                {
                    case DialogResult.Yes:
                        Process.Start("http://download.live.com/wlmail");
                        return;
                        break;
                    case DialogResult.Cancel:
                        return;
                        break;
                }
            }

            Process.Start(msgFile.FullName);
            messageGrid.Refresh();
        }
Пример #58
0
 public AnimationContent(MessageViewModel message)
 {
     InitializeComponent();
     UpdateMessage(message);
 }
        public EmailView()
        {
            InitializeComponent();

            BindingContext = new MessageViewModel("Email");
        }
Пример #60
0
        public ActionResult CreateMessage()
        {
            var outmodel = new MessageViewModel
            {
               DisplayMode = false
            };

            return View(outmodel);
        }