/// <summary> /// 根据消息Id查询消息发送对象的信息 /// </summary> /// <param name="messageId"></param> /// <returns></returns> public static MessageToUser GetMessageToUserByMessageId(int messageId) { string sql = "select * from MessageToUser where MessageId=" + messageId; try { SqlDataReader reader = DBHelper.GetReader(sql); if (reader.Read()) { MessageToUser item = new MessageToUser(); item.Id = (int)reader["Id"]; item.IfRead = (int)reader["IfRead"]; int msgId = (int)reader["MessageId"]; string userId = (string)reader["ToUserId"]; reader.Close(); item.Message = MessageService.GetMessageById(msgId); item.ToUser = UserService.GetUserById(userId); return(item); } else { reader.Close(); return(null); } } catch (Exception ex) { throw new ApplicationException(ex.Message); } }
protected void gvPersonMessageInfo_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor"); Message msg = (Message)gvPersonMessageInfo.DataKeys[e.Row.RowIndex].Value; for (int i = 1; i < e.Row.Cells.Count; i++) { e.Row.Cells[i].Attributes.Add("onclick", "ScanSendMessageDetail('" + msg.MessageId + "')"); } string what = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Message.Type.MessageTypeName")); if (what.Equals("紧急消息")) { e.Row.Cells[4].Style.Add("color", "red"); } MessageToUser toUser = MessageToUserManager.GetMessageToUserByMessageId(msg.MessageId); if (toUser.IfRead == 0) { Image img = new Image(); img.ImageUrl = "../../Images/new.gif"; e.Row.Cells[2].Controls.Add(img); } } }
private void sp_UserCheck_Tap(object sender, System.Windows.Input.GestureEventArgs e) { MessageBoxResult result = MessageBox.Show("Do you want to check the user's resourse have been recycled!", "Check", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { StackPanel sp = (StackPanel)sender; (sp.Children[0] as Image).Source = new BitmapImage(new Uri("/Image_Volunteer/finished.png", UriKind.Relative)); RecyclePlanModel model = ((StackPanel)sender).DataContext as RecyclePlanModel; MessageToUser message1 = new MessageToUser() { FromId = (App.Current as App).UserId, ToId = model.UserId, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 2, }; vm.db.RecyclePlanShips.First(c => c.Id == model.ShipId).IsCheck = true; message1.MessageContent = "Volunteer " + (App.Current as App).Userinfo.UserName; message1.MessageContent += " resourse in your area,Do you want to confirm that these resourses have been recycled?"; page.client.SendMessageToUserAsync(message1); } else { RecyclePlanModel model = ((StackPanel)sender).DataContext as RecyclePlanModel; vm.db.RecyclePlanShips.First(c => c.Id == model.ShipId).IsCheck = false; StackPanel sp = (StackPanel)sender; (sp.Children[0] as Image).Source = new BitmapImage(new Uri("/Image_Volunteer/X.png", UriKind.Relative)); } }
/// <summary> /// Creates 'MessageToUser' for every user which has currently conversation with currently logged in user '_activeUser'. /// </summary> /// <returns>Void</returns> private async Task LoadConversations() { using (var _dbContext = new MessengerContext()) { _dbContext.Users.Attach(_activeUser); // Add users who have conversation with currently logged user var _receivers = await _dbContext.Conversations .Where(x => x.FirstUser.UserId == _activeUser.UserId) .Select(x => x.SecondUser) .ToListAsync(); _receivers.AddRange(await _dbContext.Conversations .Where(x => x.SecondUser.UserId == _activeUser.UserId) .Select(x => x.FirstUser) .ToListAsync()); // Create 'MessageToUser' for every receiver foreach (var _receiver in _receivers) { var _messageToUser = new MessageToUser(this, _receiver, _activeUser); this.flowlayoutMessages.Controls.Add(_messageToUser); _openConversations.Add(_receiver); } } }
public ConcurrentQueue <RecognitionInfo> MakePrediction(List <String> images) //doesnt check in db context { MessageToUser?.Invoke(this, "If you want to stop recognition press ctrl + C"); CancellationToken token = cancel.Token; try { ParallelOptions po = new ParallelOptions(); po.CancellationToken = token; po.MaxDegreeOfParallelism = Environment.ProcessorCount; var tasks = Parallel.ForEach <string>(images, po, img => { CQ.Enqueue(ProcessImage(img)); OutputResult?.Invoke(this, CQ); }); } catch (OperationCanceledException) { MessageToUser?.Invoke(this, "-----------------Interrupted-----------------"); Trace.WriteLine("-----------------Interrupted-----------------"); } catch (Exception e) when(e is ArgumentException || e is IOException) { Trace.WriteLine(e.Message); }; return(CQ); }
/// <summary> /// 光棒效果 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void gvMessage_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'"); e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor"); HyperLink hl = e.Row.FindControl("hlSendObject") as HyperLink; MessageToUser item = MessageToUserManager.GetMessageToUserByMessageId(Convert.ToInt32(hl.Text.Trim())); //给消息类型加色 string what = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Type.MessageTypeName")); if (what.Equals("紧急消息")) { e.Row.Cells[1].Style.Add("color", "red"); } if (item.ToUser == null) { hl.Text = "所有用户"; } else { hl.NavigateUrl = "javascript:ScanReceiveUsers(" + hl.Text.Trim() + ")"; hl.Text = "查看发送用户名"; } int ifPublish = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "IfPublish")); if (ifPublish == 1) { ImageButton imgBtnUpdate = e.Row.FindControl("imgBtnUpdate") as ImageButton; //e.Row.Cells[8].Style.Add("background-color", "#999999"); imgBtnUpdate.BackColor = Color.Gray; } } }
public override void ValueChanged(object sender, BaseEntity entity) { Control control = (Control)sender; Ferier ferier = (Ferier)entity; switch (control.Name) { case "dateDebutDateTimePicker": { ferier.DateFin = ferier.DateDebut; } break; case "dateFinDateTimePicker": { if (ferier.DateFin < ferier.DateDebut) { ferier.DateFin = ferier.DateDebut; MessageToUser.AddMessage(MessageToUser.Category.BusinessRule, "La date de fin ne peut pas être ingférieur de la date de début"); } } break; default: break; } }
public ActionResult UserProfile(UserPost userPost, HttpPostedFileBase file) { if (Session["UserId"] != null) { //all user basic onfo User aUser = aManager.GetAllUserInfo(Convert.ToInt32(Session["UserId"])); ViewBag.User = aUser; // all status from user db ViewData["AllStatus"] = aManager.GetAllPostbyUserID(Convert.ToInt32(Session["UserId"])); //latest post ViewData["LatestPost"] = db.Post.OrderByDescending(p => p.Time).Take(2); //admin message MessageToUser aMessageToUser = db.TblToUser.FirstOrDefault(); ViewBag.MessageToUser = aMessageToUser; userPost.UserId = Convert.ToInt32(Session["UserId"]); userPost.Time = DateTime.Now; userPost.Author = Session["Author"].ToString(); if (file == null) { userPost.Image = "Images/" + "logo.jpg"; } else { string filename = System.IO.Path.GetFileName(file.FileName); /*Saving the file in server folder*/ file.SaveAs(Server.MapPath("~/Images/" + filename)); userPost.Image = "Images/" + filename; } if (ModelState.IsValid) { db.Post.Add(userPost); db.SaveChanges(); return(RedirectToAction("UserProfile")); } return(View(userPost)); } return(RedirectToAction("Login")); }
public string SendMessageToUser(MessageToUser message) { List <Uri> list = new List <Uri>(); if (message.Type == 1) { Console.WriteLine("type: 1" + message.FromId + "--" + message.ToId); MessageToUserTable table = new MessageToUserTable() { FromId = message.FromId, ToId = message.ToId, Type = 1, MessageContent = message.MessageContent, Time = message.Time, IsSee = false, }; db.MessageToUserTables.AddObject(table); db.SaveChanges(); if (RegistrationService.GetSubscribers().Keys.Contains(message.ToId)) { list.Add(RegistrationService.GetSubscribers()[message.ToId]); notifier.SendTileNotification(list, "", "", 1, "", null); string UserName = db.AcquirerTables.SingleOrDefault(c => c.Id == message.FromId).UserName; Console.WriteLine("From " + UserName + " To " + message.ToId + " MessageContent:" + message.MessageContent); notifier.SendToastNotification(list, UserName, message.MessageContent, null); } } if (message.Type == 2) { MessageToUserTable table2 = new MessageToUserTable() { FromId = message.FromId, ToId = message.ToId, Type = 2, MessageContent = message.MessageContent, Time = message.Time, IsSee = false, }; db.MessageToUserTables.AddObject(table2); db.SaveChanges(); Console.WriteLine("type: 2"); if (RegistrationService.GetSubscribers().Keys.Contains(message.ToId)) { list.Add(RegistrationService.GetSubscribers()[message.ToId]); notifier.SendTileNotification(list, "", "", 1, "", null); Console.WriteLine("From System Message to " + +message.ToId + " MessageContent:" + message.MessageContent); notifier.SendToastNotification(list, "System Message", message.MessageContent, null); } } return("OK"); }
/// <summary> /// 修改消息 /// </summary> /// <param name="messageId"></param> /// <param name="toUserId"></param> /// <param name="IfRead"></param> /// <returns></returns> public static int UpdateMessageToUser(MessageToUser item) { string sql = "update MessageToUser set messageId=@messageId,ToUserId=@ToUserId,IfRead=@IfRead where Id=@Id"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@messageId", item.Message.MessageId), new SqlParameter("@ToUserId", item.ToUser.UserId), new SqlParameter("@IfRead", item.IfRead), new SqlParameter("@Id", item.Id) }; return(DBHelper.ExecuteCommand(sql, para)); }
void btn_Send_Tap(object sender, System.Windows.Input.GestureEventArgs e) { // btnRoute.IsEnabled = true; mapClear(); string time = (string)control_TiemMenu.time.SelectedItem; time = control_TiemMenu.date.ValueString + " " + time; int planId = vm.saveRecyclePlan(acquirerId, time); foreach (UserModel user in list_User_Choosed) { vm.saveRecycleShip(planId, user.Id); MessageToUser message = new MessageToUser() { FromId = acquirerId, ToId = user.Id, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 1, }; MessageToUser message1 = new MessageToUser() { FromId = acquirerId, ToId = user.Id, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 2, }; List <int> list = new List <int>(); foreach (ItemModel item in list_Item_Choosed.Where(c => c.UserId == user.Id)) { if (!list.Contains(item.CategoryId - 1)) { list.Add(item.CategoryId - 1); } } // "Hust recycle bin recycle paper resourse in your area and your paper cups,paper box are in the confines .Do you want to confirm that these resourses have been recycled? message.MessageContent = vm.acquirerInfo.BinName + " will come to recycle "; message1.MessageContent = vm.acquirerInfo.BinName + "recycle"; for (int i = 0; i < list.Count - 1; i++) { message.MessageContent += AcquirerVM.categoryStr[list[i]] + " & "; // message1.MessageContent+=AcquirerVM.categoryStr[i]+ " & "; } message.MessageContent += AcquirerVM.categoryStr[list[list.Count - 1]] + " "; message1.MessageContent += AcquirerVM.categoryStr[list[list.Count - 1]] + " "; message.MessageContent += "in your area in " + control_TiemMenu.date.ValueString + " " + control_TiemMenu.time.SelectedItem; message1.MessageContent += "resourse in your area,Do you want to confirm that these resourses have been recycled?"; client.SendMessageToUserAsync(message); // client.SendMessageToUserAsync(message1); } }
// Handles the click event on 'sendNewMessageButton' private async void SendNewMessageButton_Click(object sender, EventArgs e) { // Check if user is logged in if (_activeUser == null) { MessageBox.Show("You need to log in first!", "LogIn", MessageBoxButtons.OK, MessageBoxIcon.Error); SwitchNewMessageOverlay(); return; } var _receiverName = receiverComboBox.SelectedItem as string; using (var _db = new MessengerContext()) { // Get user from DB as <User> var _receiver = await _db.Users .FirstOrDefaultAsync(x => x.Username.Equals(_receiverName)); // Check for invalid receiver if (_receiver == null || _receiver.UserId == _activeUser.UserId) { Console.WriteLine("DEBUG: Tried to add MessageToUser to same user as currently logged, or receiver was null."); return; } // Check for already open conversations if (_openConversations.SingleOrDefault(x => x.UserId == _receiver.UserId) != null) { foreach (Control _messagesControl in this.flowlayoutMessages.Controls) { var _msg = _messagesControl as MessageToUser; if (_msg.CheckUserSimilarityAndClick(_receiver)) { return; } } } // Conversation with new user var _messageToUser = new MessageToUser(this, _receiver, _activeUser); this.flowlayoutMessages.Controls.Add(_messageToUser); _openConversations.Add(_receiver); _messageToUser.OpenConversation(); } SwitchNewMessageOverlay(); }
public ActionResult AdminWorld(MessageToUser message) { //ADMIN INFO if (Session["Adminid"] == null) { return(RedirectToAction("Login")); } AdminControl admin = db.TblAdminControls.Find(Session["Adminid"]); if (admin == null) { return(RedirectToAction("Login")); } ViewBag.AdminControl = admin; //ADMIN INFO ends here //last 5 New User ViewData["LatestNewUser"] = db.Users.OrderByDescending(i => i.UserId).Take(5); //last 5 Post ViewData["Latestpost"] = db.Post.OrderByDescending(p => p.Time).Take(5); //totaluser int a = db.Users.Count(); ViewBag.Value = a; //total Post int b = db.Post.Count(); ViewBag.TotalPost = b; //set date for user message message.Date = DateTime.Now; if (ModelState.IsValid) { db.TblToUser.Add(message); db.SaveChanges(); return(RedirectToAction("AdminWorld")); } return(View(message)); }
public void UploadFolder(String folderPath) { MessageToUser m = new MessageToUser(); Thread startingThread = new Thread(m.UploadToS3); startingThread.Start(); TransferUtilityUploadDirectoryRequest request = new TransferUtilityUploadDirectoryRequest() { BucketName = _bucket, Directory = folderPath, SearchOption = SearchOption.AllDirectories, SearchPattern = "*.zip", KeyPrefix = "mods" }; TransferUtility directorytTransferUtility = new TransferUtility(_client); directorytTransferUtility.UploadDirectory(request); MessageBox.Show("Done uploading files to s3"); }
private void btn_Notice_Click(object sender, RoutedEventArgs e) { MenuItem menuItem = (MenuItem)sender; foreach (UserModel model in vm.getChooseUser((((KeyValuePair <string, ObservableCollection <RecyclePlanModel> >)menuItem.DataContext)).Value)) { MessageToUser message1 = new MessageToUser() { FromId = page.acquirerId, ToId = model.Id, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 1, }; message1.MessageContent = "Volunteer " + (App.Current as App).Userinfo.UserName; message1.MessageContent += " has arrived at your community! now you can take you resourse to recycler!"; page.client.SendMessageToUserAsync(message1); } }
/// <summary> /// Set Ressouce Manager of the entity and All its BaseEntity /// </summary> public static void FillResourcesManager(Type type_entity, Dictionary <string, ResourceManager> RessoucesManagers) { string RessouceFullName = type_entity.Namespace + ".Resources." + type_entity.Name + "." + type_entity.Name; if (new RessoucesManagerHelper().ResourceExists(RessouceFullName)) { RessoucesManagers.Add(type_entity.Name, new ResourceManager(RessouceFullName, type_entity.Assembly)); } else { MessageToUser.AddMessage(MessageToUser.Category.BusinessRule, "The resource file does not exist : " + RessouceFullName); return; } if (type_entity.BaseType != typeof(object)) { FillResourcesManager(type_entity.BaseType, RessoucesManagers); } }
/// <summary> /// 根据消息ID和用户ID查询消息发送对象信息 /// </summary> /// <param name="messageId"></param> /// <returns></returns> public static MessageToUser GetMessageToUserByMessageIdandUserId(string userId, int messageId) { string sql = "select * from MessageToUser where MessageId=" + messageId + " and ToUserId='" + userId + "'"; sql += " union select * from MessageToUser where MessageId=" + messageId + " and ToUserId='0'"; using (DataTable dt = DBHelper.GetDataSet(sql)) { MessageToUser item = new MessageToUser(); foreach (DataRow row in dt.Rows) { item.Id = (int)row["Id"]; item.IfRead = (int)row["IfRead"]; item.Message = MessageService.GetMessageById(messageId); item.ToUser = UserService.GetUserById(userId); } return(item); } }
private static IList <MessageToUser> GetMessageToUserBySql(string sql) { IList <MessageToUser> list = new List <MessageToUser>(); using (DataTable dt = DBHelper.GetDataSet(sql)) { foreach (DataRow row in dt.Rows) { MessageToUser item = new MessageToUser(); item.Id = (int)row["Id"]; item.IfRead = (int)row["IfRead"]; item.Message = MessageService.GetMessageById((int)row["MessageId"]); item.ToUser = UserService.GetUserById((string)row["ToUserId"]); list.Add(item); } return(list); } }
private void btn_Notice_Click(object sender, RoutedEventArgs e) { MenuItem menuItem = (MenuItem)sender; foreach(UserModel model in vm.getChooseUser((((KeyValuePair<string, ObservableCollection<RecyclePlanModel>>)menuItem.DataContext)).Value)) { MessageToUser message1 = new MessageToUser() { FromId = ((AcquirerPage)page).acquirerId, ToId = model.Id, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 1, }; message1.MessageContent = ((AcquirerPage)page).vm.acquirerInfo.BinName + " Recycler "; message1.MessageContent += "has arrived at your community! now you can take you resourse to recycler!"; ((AcquirerPage)page).client.SendMessageToUserAsync(message1); } }
public void DbEntityValidationExceptionTreatment(DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; BaseEntity entity = (BaseEntity)entry.Entity; string entityTypeName = entity.ToString(); // Display or log error messages foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Erreur : '{0}' \n trouvé dans l'objet : {1} \n sur la propriété {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); MessageToUser.AddMessage(MessageToUser.Category.EntityValidation, message); } } }
public List <MessageToUser> GetMessge(int userId) { List <MessageToUser> list = new List <MessageToUser>(); foreach (MessageToUserTable item in db.MessageToUserTables.Where(c => c.ToId == userId && c.IsSee == false)) { if (item.Type == 1) { string name = ""; AcquirerTable acquirer = db.AcquirerTables.FirstOrDefault(c => c.Id == item.FromId); UserTable user = db.UserTables.FirstOrDefault(c => c.Id == item.FromId); if (acquirer != null) { name = acquirer.UserName; } if (user != null) { name = user.UserName; } MessageToUser message = new MessageToUser() { Name = name, FromId = item.FromId, MessageContent = item.MessageContent, Type = item.Type }; list.Add(message); item.IsSee = true; } else { MessageToUser message = new MessageToUser() { MessageContent = item.MessageContent, Type = item.Type }; item.IsSee = true; list.Add(message); } } db.SaveChanges(); return(list); }
public void UploadFolder(String folderPath) { String[] files; if (Directory.Exists(folderPath)) { files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories); } else { Debug.WriteLine("No files was created, so no reason to upload anything"); return; } MessageToUser m = new MessageToUser(); Thread startingThread = new Thread(m.UploadingToFtp); startingThread.Start(); foreach (String file in files) { UploadFile(file, file.Replace(folderPath + Globalfunctions.PathSeperator, ""), "mods"); } }
/// <summary> /// 添加 /// </summary> /// <param name="item"></param> /// <returns></returns> public static bool AddMessageToUser(MessageToUser item) { string sql = "insert into MessageToUser(MessageId,ToUserId,IfRead) values(@MessageId,@ToUserId,@IfRead)"; sql += " ;select @@Identity"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@MessageId", item.Message.MessageId), new SqlParameter("@ToUserId", item.ToUser.UserId), new SqlParameter("@IfRead", item.IfRead) }; int id = Convert.ToInt32(DBHelper.GetScalar(sql, para)); if (id > 0) { return(true); } else { return(false); } }
public void SQLExceptionTreatment(SqlException sqlException) { if (sqlException != null) { if (sqlException.Errors.Count > 0) { switch (sqlException.Errors[0].Number) { case 547: // Foreign Key violation MessageToUser.AddMessage(MessageToUser.Category.ForeignKeViolation, ""); break; default: throw (sqlException); } } } else { throw (sqlException); } }
public ActionResult UserProfile() { if (Session["UserId"] != null) { //all user basic onfo User aUser = aManager.GetAllUserInfo(Convert.ToInt32(Session["UserId"])); ViewBag.User = aUser; // all status from user db ViewData["AllStatus"] = aManager.GetAllPostbyUserID(Convert.ToInt32(Session["UserId"])); //latest post ViewData["LatestPost"] = db.Post.OrderByDescending(p => p.Time).Take(3); //admin message MessageToUser aMessageToUser = db.TblToUser.FirstOrDefault(); ViewBag.MessageToUser = aMessageToUser; return(View()); } return(RedirectToAction("Login")); }
public virtual void DbUpdateExceptionTreatment(DbUpdateException e) { var sqlException = e.GetBaseException() as SqlException; if (sqlException != null) { if (sqlException.Errors.Count > 0) { switch (sqlException.Errors[0].Number) { case 547: // Foreign Key violation MessageToUser.AddMessage(MessageToUser.Category.ForeignKeViolation, ""); break; default: throw (sqlException); } } } else { throw (sqlException); } }
internal void OnMessageToUser(SessionEventArgs e) { MessageToUser.RaiseEvent(this, e); }
void btn_Send_Tap(object sender, System.Windows.Input.GestureEventArgs e) { // btnRoute.IsEnabled = true; mapClear(); string time = (string)control_TiemMenu.time.SelectedItem; time = control_TiemMenu.date.ValueString + " " + time; int planId = vm.saveRecyclePlan(acquirerId, time); foreach (UserModel user in list_User_Choosed) { vm.saveRecycleShip(planId, user.Id); MessageToUser message = new MessageToUser() { FromId = acquirerId, ToId = user.Id, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 1, }; List<int> list = new List<int>(); foreach (ItemModel item in list_Item_Choosed.Where(c => c.UserId == user.Id)) { if (!list.Contains(item.CategoryId-1)) list.Add(item.CategoryId-1); } // "Hust recycle bin recycle paper resourse in your area and your paper cups,paper box are in the confines .Do you want to confirm that these resourses have been recycled? message.MessageContent = "Volunteer "+vm.acquirerInfo.UserName + " will come to recycle "; for (int i = 0; i < list.Count - 1; i++) { message.MessageContent += AcquirerVM.categoryStr[list[i]] + " & "; } message.MessageContent += AcquirerVM.categoryStr[list[list.Count - 1]] + " "; message.MessageContent += "in your area in " + control_TiemMenu.date.ValueString + " " + control_TiemMenu.time.SelectedItem; client.SendMessageToUser_VAsync(message); // client.SendMessageToUserAsync(message1); } }
public void ReceiveTextMessage(MessageToUser message) => TextMessageController?.GetTextMessageFromUser(message.Username, message.Text);
public ConcurrentQueue <RecognitionInfo> MakePrediction(Dictionary <string, string> info) //doesnt check in db context { MessageToUser?.Invoke(this, "If you want to stop recognition press ctrl + C"); CancellationToken token = cancel.Token; try { ParallelOptions po = new ParallelOptions(); po.CancellationToken = token; po.MaxDegreeOfParallelism = Environment.ProcessorCount; Dictionary <string, string> temp_info = new Dictionary <string, string>(); lock (recognitionLibraryContext) { foreach (var image in info) { RecognitionInfo temp = new RecognitionInfo(image.Key, "", 0); temp.Image = Convert.FromBase64String(image.Value); var sameimage = recognitionLibraryContext.FindOne(temp); if (sameimage != null) { sameimage.Statistic++; Trace.WriteLine("Statisticv " + sameimage.Statistic); recognitionLibraryContext.SaveChanges(); } else { Trace.WriteLine("Const temp_info " + image.Key); temp_info.Add(image.Key, image.Value); } } } var task = Task.Factory.StartNew(() => { Trace.WriteLine("StartNew"); foreach (var img in temp_info) { var t = Task.Run(() => { var tmp = ProcessImage(Convert.FromBase64String(img.Value), img.Key); Trace.WriteLine("Start nFactory = " + tmp.Path); CQ.Enqueue(tmp); OutputResult?.Invoke(this, CQ); }, cancel.Token); Task.WaitAll(t); } }); Task.WaitAll(task); } catch (OperationCanceledException) { MessageToUser?.Invoke(this, "-----------------Interrupted-----------------"); Trace.WriteLine("-----------------Interrupted-----------------"); } catch (Exception e) when(e is ArgumentException || e is IOException) { Trace.WriteLine(e.Message); }; return(CQ); }
public ConcurrentQueue <RecognitionInfo> MakePrediction(string path) //should check dbcontext { MessageToUser?.Invoke(this, "If you want to stop recognition press ctrl + C"); CancellationToken token = cancel.Token; try { IEnumerable <string> images; ParallelOptions po = new ParallelOptions(); po.CancellationToken = token; po.MaxDegreeOfParallelism = Environment.ProcessorCount; if (path == "") // Если пользователь передал пустую директорию, меняем на дефолтную директори проекта с тестовыми изображениями { MessageToUser?.Invoke(this, "You haven't set the path. Changed to embedded directory with images"); images = from file in Directory.GetFiles(DefaultImageDir) where file.Contains(".jpg") || file.Contains(".jpeg") || file.Contains(".png") select file; } images = from file in Directory.GetFiles(path) // пустой путь - throw exception where file.Contains(".jpg") || file.Contains(".jpeg") || file.Contains(".png") select file; if (images.Count() == 0) // Если пользователь передал пустую директорию, меняем на дефолтную директори проекта с тестовыми изображениями { MessageToUser?.Invoke(this, "Your directory is empty. Change to embedded directory with images"); images = from file in Directory.GetFiles(DefaultImageDir) where file.Contains(".jpg") || file.Contains(".jpeg") || file.Contains(".png") select file; } List <string> paths = new List <string>(); lock (recognitionLibraryContext) { foreach (var image in images) { RecognitionInfo temp = new RecognitionInfo(image, "", 0); var sameimage = recognitionLibraryContext.FindOne(temp); if (sameimage != null) { sameimage.Statistic++; recognitionLibraryContext.SaveChanges(); } else { paths.Add(image); } } } var task = Task.Factory.StartNew(() => { Trace.WriteLine("StartNew"); foreach (var img in images) { var t = Task.Run(() => { var tmp = ProcessImage(img); CQ.Enqueue(tmp); OutputResult?.Invoke(this, CQ); }, cancel.Token); } }); task.Wait(); Trace.WriteLine("After wait"); } catch (OperationCanceledException) { MessageToUser?.Invoke(this, "-----------------Interrupted-----------------"); Trace.WriteLine("-----------------Interrupted-----------------"); } catch (Exception e) when(e is ArgumentException || e is IOException) { Trace.WriteLine(e.Message); }; return(CQ); }
private void sp_UserCheck_Tap(object sender, System.Windows.Input.GestureEventArgs e) { MessageBoxResult result= MessageBox.Show("Do you want to check the user's resourse have been recycled!","Check",MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { StackPanel sp = (StackPanel)sender; (sp.Children[0] as Image).Source = new BitmapImage(new Uri("/Image_Volunteer/finished.png", UriKind.Relative)); RecyclePlanModel model = ((StackPanel)sender).DataContext as RecyclePlanModel; MessageToUser message1 = new MessageToUser() { FromId = ((AcquirerPage)page).acquirerId, ToId = model.UserId, Time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(), Type = 2, }; vm.db.RecyclePlanShips.First(c => c.Id == model.ShipId).IsCheck = true; message1.MessageContent = ((AcquirerPage)page).vm.acquirerInfo.BinName + " recycle"; message1.MessageContent += " resourse in your area,Do you want to confirm that these resourses have been recycled?"; ((AcquirerPage)page).client.SendMessageToUserAsync(message1); } else { RecyclePlanModel model = ((StackPanel)sender).DataContext as RecyclePlanModel; vm.db.RecyclePlanShips.First(c => c.Id == model.ShipId).IsCheck = false; StackPanel sp = (StackPanel)sender; (sp.Children[0] as Image).Source = new BitmapImage(new Uri("/Image_Volunteer/X.png", UriKind.Relative)); } }
public void ReceiveTextMessage(MessageToUser message) => _clientCallback?.ReceiveTextMessage(message);