/* * Compose final message to be sent * * -- * AA 55 60 01 7F 7F 7F 7F 01 01 01 5F * AA 55 6e tt rr ee aa gg tt 01 01 cc * -- * * Placeholders: * e = 1 -> enable wifi control * tt = throttle, 01 = min (off), ff = max (comes twice !) * rr = rudder, 01 = min, 7f = center, ff = max * ee = elevation * aa = aileron * gg = gyro * cc = checksum */ public void OnPositionMessageModelChanged(MessageModel positionMessageModel) { // use string builder instead of regular string and concatenate method - much better mem management StringBuilder constructedMessage = new StringBuilder(); //compose string message from model // AA 55 - package start constructedMessage.Append(positionMessageModel.PackageStart.ToString("X4")); // 6e - WiFi control constructedMessage.Append(positionMessageModel.WiFiControl.ToString("X2")); // tt - throttle constructedMessage.Append(positionMessageModel.Throttle.ToString("X2")); // rr - rudder constructedMessage.Append(positionMessageModel.Rudder.ToString("X2")); // ee - elevator constructedMessage.Append(positionMessageModel.Elevator.ToString("X2")); // aa - aileron constructedMessage.Append(positionMessageModel.Aileron.ToString("X2")); // gg - gyro constructedMessage.Append(positionMessageModel.Gyro.ToString("X2")); // tt - throttle constructedMessage.Append(positionMessageModel.Throttle.ToString("X2")); // 01 01 - package end constructedMessage.Append(positionMessageModel.PackageEnd.ToString("X4")); // cc - checksum // calculate checksum and add it at the end of message string checksum = Utils.CalculateChecksum(constructedMessage.ToString()); constructedMessage.Append(checksum); // convert string to byte array _commandMessage = Utils.HexString2Bytes(constructedMessage.ToString()); }
MessageModel GetMessage(int idx) { MessageModel model = new MessageModel(); model.MessageId = Guid.NewGuid(); model.Subject = "Message #" + idx.ToString(); model.Body = "Message Body Here"; model.LastUpdate = DateTime.Now.AddDays(-1); return model; }
public static void SendConfirmationEmail(MessageModel model) { MembershipUser user = Membership.GetUser(model.UserName); var message = new MailMessage("*****@*****.**", user.Email) { Subject = model.MessageSubject, Body = model.MessageBody }; var client = new SmtpClient(); client.Send(message); }
public IHttpActionResult Send(MessageModel message) { string AccountSid = CloudConfigurationManager.GetSetting("AccountSid"); string AuthToken = CloudConfigurationManager.GetSetting("AuthToken"); string FromNumber = CloudConfigurationManager.GetSetting("FromNumber"); var twilio = new TwilioRestClient(AccountSid, AuthToken); var twilioMessage = twilio.SendMessage(FromNumber, message.ToNumber, message.Text); Console.WriteLine(twilioMessage.Sid); return Ok(); }
public MessageDtoModelV1(MessageModel msg) { if (msg == null) { throw new ArgumentNullException("msg"); } TimeStamp = msg.TimeStamp; MessageType = msg.MessageType; MessageParts = new List<MessagePartDtoModelV1>(msg.MessageParts.Count); foreach (var msgPart in msg.MessageParts) { var dtoPart = new MessagePartDtoModelV1(msgPart); MessageParts.Add(dtoPart); } }
/* * Default constructor */ public QuadController() { // create positions model and set default values _positions = new MessageModel(); ResetPositions(); // instantiate services _protocolServices = new ProtocolServices(); // init HID Transmitter device InitHIDTransmitter(); Connect(); }
public IHttpActionResult PostMessage(MessageModel message) { var sender = db.Users.FirstOrDefault(u => u.UserName == message.SenderUserName); var newMessage = new PublicMessage() { Text = message.Message, DateTime = message.DateSent, SenderId = sender.Id }; db.PublicMessages.Add(newMessage); db.SaveChanges(); return Ok(message); }
public virtual MessageModel ToMessage() { var msg = new MessageModel() { MessageType = this.MessageType, TimeStamp = this.TimeStamp }; foreach (var msgPart in MessageParts) { MessagePartModel part = null; switch (msgPart.Type) { case "Text": var textPart = new TextMessagePartModel() { ForegroundColor = msgPart.ForegroundColor, BackgroundColor = msgPart.BackgroundColor, Underline = msgPart.Underline, Bold = msgPart.Bold, Italic = msgPart.Italic, Text = msgPart.Text }; part = textPart; break; case "URL": var urlPart = new UrlMessagePartModel() { Url = msgPart.Url, Text = msgPart.Text }; part = urlPart; break; case "Image": var imagePart = new ImageMessagePartModel() { ImageFileName = msgPart.ImageFileName, AlternativeText = msgPart.AlternativeText }; part = imagePart; break; } if (part == null) { continue; } part.IsHighlight = msgPart.IsHighlight; msg.MessageParts.Add(part); } return msg; }
private static int CompareTasks(MessageModel x, MessageModel y) { if (x.ClientMessageId == y.ClientMessageId) { return 0; } if (x.IsPullDown) { return -1; } if (y.IsPullDown) { return 1; } return x.PostDateTimeUtcTicks > y.PostDateTimeUtcTicks ? -1 : 1; }
void processResponse(HTTPRequest req, HTTPResponse res) { Debug.Log (res.DataAsText); JsonReader json = new JsonReader (res.DataAsText); json.SkipNonMembers = true; NewQuestionModel response = JsonMapper.ToObject<NewQuestionModel> (json); Debug.Log (response.success); if (response.success != null) { MessageModel message = new MessageModel(); if (response.success) { message.title = _i18n.get("MESSAGE_TITLE_OK"); message.text = _i18n.get("MESSAGE_NEW_CHALLENGE_OK"); message.color = Properties.colorRight; } else { message.title = _i18n.get("MESSAGE_TITLE_ERROR"); message.text = _i18n.get("MESSAGE_NEW_CHALLENGE_ERROR"); message.color = Properties.colorWrong; } _dispatcher.Dispatch("message_update", message); } }
public void AddMessage(MessageModel message) { Messages.Add(message); }
public MessageModel Put(string id, [FromBody] MessageModel body) { _messages.Update(id, body); return(_messages.GetOneEnabled(id)); }
private void AddTask(MessageModel task) { if (task == null) { return; } DispatcherHelper.InvokeOnUiThread(() => { if (task.IsTaskMessage.Value) { for (int i = 0; i < this.tasks.Count; i++) { if (this.tasks[i].ClientMessageId == task.ClientMessageId) { this.tasks.RemoveAt(i); if (!task.IsTaskDeleted.HasValue || !task.IsTaskDeleted.Value) { this.tasks.Add(task); } return; } } if (!task.IsTaskDeleted.HasValue || !task.IsTaskDeleted.Value) { this.tasks.Add(task); } } }); }
public async Task <bool> AddMessage(MessageModel message) { _context.Messages.Add(message); return(await _context.SaveChangesAsync() > 0); }
public void Post([FromBody] MessageModel msg) { _logger.LogInformation($"Message was {msg.Message}"); }
/// <summary> /// Send new message /// </summary> public void SendMessage(MessageModel newMessageToSend) { Messenger.Default.Send<NewMessageSavedEvent>(new NewMessageSavedEvent() { Message = newMessageToSend }); BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (o, f) => { if (!newMessageToSend.IsTaskMessage.Value && !newMessageToSend.IsTaskItemMessage) { InsertMessageToDBBeforeSending(newMessageToSend); } // If poll message has not been sent, don't send the poll response if (!newMessageToSend.IsPollResponseMessage || (newMessageToSend.PollMessageId.Value != Guid.Empty)) { this.serviceProxy.SendNewMessage(newMessageToSend.EncryptMessage(), this.NewMessageCreated); } }; worker.RunWorkerAsync(); }
private void btnSave2_Click(object sender, EventArgs e) { try { DAL.Model.OutdoorPatient aOutdoorPatient = new DAL.Model.OutdoorPatient(); aOutdoorPatient.Opid = txtOpid.Text; aOutdoorPatient.ServiceDate = fromDate.Value; if (cmbTreatmentType.Text == "All" || cmbTreatmentType.Text == "IPD" || cmbTreatmentType.Text == "Emergency" || cmbTreatmentType.Text == "Daycare" || cmbTreatmentType.Text == "Consultation") { aOutdoorPatient.TreatementType = cmbTreatmentType.Text; } aOutdoorPatient.PatientName = txtPatientName.Text; aOutdoorPatient.GurdianName = txtGurdianName.Text; aOutdoorPatient.Address = txtAddress.Text; aOutdoorPatient.Phone = txtPhone.Text; if (!string.IsNullOrEmpty(txtAge.Text) && txtAge.Text != "") { aOutdoorPatient.Age = Convert.ToInt32(txtAge.Text); } if (cmbBloodGroup.Text == "A+" || cmbBloodGroup.Text == "A-" || cmbBloodGroup.Text == "AB+" || cmbBloodGroup.Text == "AB-" || cmbBloodGroup.Text == "B+" || cmbBloodGroup.Text == "B-" || cmbBloodGroup.Text == "O+" || cmbBloodGroup.Text == "O-" || cmbBloodGroup.Text == "N/A") { aOutdoorPatient.BloodGroup = cmbBloodGroup.Text; } if (cmbGender.Text == "Female" || cmbGender.Text == "Male" || cmbGender.Text == "Neuture") { aOutdoorPatient.Gender = cmbGender.Text; } aOutdoorPatient.Nationality = cmbNationality.Text; aOutdoorPatient.ContactPerson = txtContactPerson.Text; aOutdoorPatient.Mobile = txtMobileContactPerson.Text; aOutdoorPatient.RefferedBy = string.IsNullOrEmpty(cmbRefferedBy.SelectedValue.ToString()) ? null : cmbRefferedBy.SelectedValue.ToString(); aOutdoorPatient.AService = new Service(); aOutdoorPatient.AService.OPID = txtOpid.Text; aOutdoorPatient.AService.ServiceId = "Serv-02"; if (!string.IsNullOrEmpty(txtDoctorFees.Text)) { aOutdoorPatient.AService.Rate = Convert.ToDouble(txtDoctorFees.Text); } aOutdoorPatient.AService.Qty = 1; aOutdoorPatient.AService.IssueDate = DateTimeServiceDate.Value; aOutdoorPatient.ServiceDate = DateTimeServiceDate.Value; if (searchLookUpDoctor.Properties.View.GetFocusedRowCellValue("DoctorID") != null) { aOutdoorPatient.Doctor = searchLookUpDoctor.Properties.View.GetFocusedRowCellValue("DoctorID").ToString(); } aOutdoorPatient.Fees = txtDoctorFees.Text; if (btnSave2.Text == "Save") { MessageModel aMessageModel = new MessageModel(); aMessageModel = aOutdoorPatientManager.SaveOutdoorPatient(aOutdoorPatient); if (aMessageModel.MessageTitle == "Successful") { MetroFramework.MetroMessageBox.Show(this, aMessageModel.MessageBody, aMessageModel.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); Refresh(); } else { MetroFramework.MetroMessageBox.Show(this, aMessageModel.MessageBody, aMessageModel.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageModel aMessageModel = new MessageModel(); aMessageModel = aOutdoorPatientManager.UpdateOutdoorPatient(aOutdoorPatient); if (aMessageModel.MessageTitle == "Successful") { MetroFramework.MetroMessageBox.Show(this, aMessageModel.MessageBody, aMessageModel.MessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); Refresh(); } else { MetroFramework.MetroMessageBox.Show(this, aMessageModel.MessageTitle, aMessageModel.MessageBody, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (Exception) { //throw; } }
public async Task <MessageModel> UpdateMessage(MessageModel newMessage) { logger.Debug($"User {Context.User.Identity.Name} update message int chat {newMessage.ChatId}"); return(await _message.UpdateMessage(newMessage)); }
/// <summary> /// Defualt constructor /// </summary> public MessageController() { model = new MessageModel(); }
public async Task <MessageModel> SendMessage(MessageModel message) { Thread.CurrentPrincipal = Context.User; logger.Debug($"User {Context.User.Identity.Name} send message to {message.ToChatName}"); return(await _message.SendMessage(message)); }
public async Task DeleteMessage(MessageModel message, bool isForMe = false) { Thread.CurrentPrincipal = Context.User; logger.Debug($"User {Context.User.Identity.Name} delete message from {message.ToChatName}"); await _message.DeleteMessage(message, isForMe); }
public virtual void AddMessage(MessageModel msg) { Trace.Call(msg); string timestamp; try { string format = (string)Frontend.UserConfig["Interface/Notebook/TimestampFormat"]; timestamp = msg.TimeStamp.ToLocalTime().ToString(format); } catch (FormatException e) { timestamp = "Timestamp Format ERROR: " + e.Message; } timestamp += " "; _OutputTextView.SelectionHangingIndent = TextRenderer.MeasureText(timestamp, _Font).Width; _OutputTextView.AppendText(timestamp); bool hasHighlight = false; foreach (MessagePartModel msgPart in msg.MessageParts) { #if LOG4NET _Logger.Debug("AddMessage(): msgPart.GetType(): " + msgPart.GetType()); #endif if (msgPart.IsHighlight) { hasHighlight = true; } // TODO: implement all types if (msgPart is UrlMessagePartModel) { UrlMessagePartModel fmsgui = (UrlMessagePartModel)msgPart; /*TODO: Create a link in the TextView (possibly requiring WinAPI hacks...)*/ _OutputTextView.SelectionColor = Color.Blue; _OutputTextView.SelectionFont = new Font(_Font, FontStyle.Underline); _OutputTextView.AppendText(fmsgui.Url); } else if (msgPart is TextMessagePartModel) { /*TODO: Add required formatting to the TextView (possibly requiring WinAPI hacks...)*/ TextMessagePartModel fmsgti = (TextMessagePartModel)msgPart; #if LOG4NET _Logger.Debug("AddMessage(): fmsgti.Text: '" + fmsgti.Text + "'"); #endif FontStyle fstyle = FontStyle.Regular; if (fmsgti.ForegroundColor == TextColor.None) { _OutputTextView.SelectionColor = _ForegroundColor ?? Color.White; } else { #if LOG4NET _Logger.Debug("AddMessage(): fmsgti.ForegroundColor: '" + fmsgti.ForegroundColor.ToString() + "'"); #endif _OutputTextView.SelectionColor = ColorTools.GetColor(fmsgti.ForegroundColor); } if (fmsgti.BackgroundColor == TextColor.None) { _OutputTextView.SelectionBackColor = _BackgroundColor ?? Color.Black; } else { #if LOG4NET _Logger.Debug("AddMessage(): fmsgti.BackgroundColor: '" + fmsgti.BackgroundColor.ToString() + "'"); #endif _OutputTextView.SelectionBackColor = ColorTools.GetColor(fmsgti.BackgroundColor); } if (fmsgti.Underline) { #if LOG4NET _Logger.Debug("AddMessage(): fmsgti.Underline is true"); #endif fstyle |= FontStyle.Underline; } if (fmsgti.Bold) { #if LOG4NET _Logger.Debug("AddMessage(): fmsgti.Bold is true"); #endif fstyle |= FontStyle.Bold; } if (fmsgti.Italic) { #if LOG4NET _Logger.Debug("AddMessage(): fmsgti.Italic is true"); #endif fstyle |= FontStyle.Italic; } _OutputTextView.SelectionFont = new Font(Font, fstyle); _OutputTextView.AppendText(fmsgti.Text); } } _OutputTextView.AppendText("\n"); // HACK: out of scope? if (hasHighlight /*&& !Frontend.MainWindow.HasToplevelFocus*/) { /*TODO: Flash the main window*/ if (Frontend.UserConfig["Sound/BeepOnHighlight"] != null && (bool)Frontend.UserConfig["Sound/BeepOnHighlight"]) { System.Media.SystemSounds.Beep.Play(); } } // HACK: out of scope? if (((TabControl)this.Parent).SelectedTab != this) { string color = null; if (hasHighlight) { _HasHighlight = hasHighlight; color = (string)Frontend.UserConfig["Interface/Notebook/Tab/HighlightColor"]; } else if (!_HasHighlight) { color = (string)Frontend.UserConfig["Interface/Notebook/Tab/ActivityColor"]; } if (color != null) { /*TODO: Color the associated Tab*/ } } }
public ChatViewMessageHighlightedEventArgs(MessageModel msg) { Message = msg; }
public MessageModel del(object obj) { MessageModel msg = new MessageModel(); return(msg); }
/// <summary> /// Get the most recent 20 messages in a conversations /// </summary> /// <param name="conversationId">ConversationId</param> /// <returns></returns> public IEnumerable<MessageModel> GetMessagesOlderThan(DataContextWrapper<YapperDataContext> context, Guid conversationId, MessageModel oldMessage, int pageSize = 5) { lock (this) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::GetMessagesOlderThan", "start")); var messages = (from message in context.Table<MessageModel>() where (message.ConversationId == conversationId && message.PostDateTimeUtcTicks <= oldMessage.PostDateTimeUtcTicks) orderby message.PostDateTimeUtcTicks descending select message).Take(pageSize); Dictionary<int, UserModel> userMessageCache = new Dictionary<int, UserModel>(); foreach (MessageModel m in messages) { UserModel senderUser = this.GetUser(m.SenderId); if (senderUser == null) { senderUser = new UserModel() { Id = m.SenderId, Name = Strings.UnknownUser }; } UserModel recipientUser = this.GetUser(m.RecipientId); if (senderUser == null) { senderUser = new UserModel() { Id = m.RecipientId, Name = Strings.UnknownUser }; } m.Sender = senderUser; m.Recipient = recipientUser; } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::GetMessagesOlderThan", "end")); return messages; } }
public async Task <MessageModel <string> > InsertPicture([FromServices] IHostingEnvironment environment) { var data = new MessageModel <string>(); string path = string.Empty; string foldername = "images"; IFormFileCollection files = null; try { files = Request.Form.Files; } catch (Exception) { files = null; } if (files == null || !files.Any()) { data.msg = "请选择上传的文件。"; return(data); } //格式限制 var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" }; string folderpath = Path.Combine(environment.WebRootPath, foldername); if (!System.IO.Directory.Exists(folderpath)) { System.IO.Directory.CreateDirectory(folderpath); } if (files.Any(c => allowType.Contains(c.ContentType))) { if (files.Sum(c => c.Length) <= 1024 * 1024 * 4) { //foreach (var file in files) var file = files.FirstOrDefault(); string strpath = Path.Combine(foldername, DateTime.Now.ToString("MMddHHmmss") + file.FileName); path = Path.Combine(environment.WebRootPath, strpath); using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { await file.CopyToAsync(stream); } data = new MessageModel <string>() { response = strpath, msg = "上传成功", success = true, }; return(data); } else { data.msg = "图片过大"; return(data); } } else { data.msg = "图片格式错误"; return(data); } }
public void NewMessageCreated(MessageModel message) { this.NewMessageCreated(message, false); }
public static void SendMessage(UserModel recipient, MessageModel message) { message.IsSent = recipient.Id % 2 == 0; }
public void SetTaskName(MessageModel message, string name, Guid parentId) { lock (this) { using (DataContextWrapper<YapperDataContext> context = new DataContextWrapper<YapperDataContext>()) { int i = 5; while (i > 0) { try { MessageModel m = this.GetMessageFromClientId(message.ClientMessageId, context); if (m == null) { context.InsertOnSubmit<MessageModel>(message); m = message; } else if (!string.IsNullOrEmpty(m.TaskName)) { m.LastTaskUpdaterId = UserSettingsModel.Instance.Me.Id; } m.TaskName = name; m.PollMessageId = parentId; m.ItemOrder = message.ItemOrder; m.LastUpdateTime = DateTime.Now; context.SubmitChanges(); break; } catch (ChangeConflictException ce) { } --i; } } } }
/// <summary> /// SendNewMessage /// </summary> /// <param name="conversationId"></param> /// <param name="message"></param> /// <param name="callback"></param> public void SendNewMessage( MessageModel messageModel, Action<MessageModel> callback) { Uri uri = new Uri(string.Format( YapperServiceProxy.SendNewMessageRelativeUrl, YapperServiceProxy.ServicePrefix)); MemoryStream stream = new MemoryStream(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MessageModel)); serializer.WriteObject(stream, messageModel); string jsonString = System.Text.Encoding.UTF8.GetString(stream.ToArray(), 0, stream.ToArray().Length); WebClient wc = new WebClient(); wc.Headers["AuthTokenCookie"] = this.GetAuthTokenCookie(); wc.Headers["Content-Type"] = "application/json; Charset=UTF-8"; //wc.Headers["Accept-Encoding"] = "gzip, deflate"; wc.UploadStringCompleted += new UploadStringCompletedEventHandler(NewMessageUploaded); Debug.WriteLine(string.Format("{0} {1} cid-{2} clientmessageid-{3} {4}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "YapperServiceProxy::SendNewMessage ", messageModel.ConversationId, messageModel.ClientMessageId, "start")); wc.UploadStringAsync(uri, null, jsonString, callback); (Application.Current as App).PerfTrackerString += "\nMsg sent:" + (Application.Current as App).PerfTrackerStopWatch.ElapsedMilliseconds.ToString(); }
/// <summary> /// 添加一个计划任务(映射程序集指定IJob实现类) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tasksQz"></param> /// <returns></returns> public async Task <MessageModel <string> > AddScheduleJobAsync(TasksQz tasksQz) { var result = new MessageModel <string>(); try { if (tasksQz != null) { JobKey jobKey = new JobKey(tasksQz.Id.ToString(), tasksQz.JobGroup); if (await _scheduler.Result.CheckExists(jobKey)) { result.success = false; result.msg = $"该任务计划已经在执行:【{tasksQz.Name}】,请勿重复启动!"; return(result); } #region 设置开始时间和结束时间 if (tasksQz.BeginTime == null) { tasksQz.BeginTime = DateTime.Now; } DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(tasksQz.BeginTime, 1);//设置开始时间 if (tasksQz.EndTime == null) { tasksQz.EndTime = DateTime.MaxValue.AddDays(-1); } DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(tasksQz.EndTime, 1);//设置暂停时间 #endregion #region 通过反射获取程序集类型和类 Assembly assembly = Assembly.Load(new AssemblyName(tasksQz.AssemblyName)); Type jobType = assembly.GetType(tasksQz.AssemblyName + "." + tasksQz.ClassName); #endregion //判断任务调度是否开启 if (!_scheduler.Result.IsStarted) { await StartScheduleAsync(); } //传入反射出来的执行程序集 IJobDetail job = new JobDetailImpl(tasksQz.Id.ToString(), tasksQz.JobGroup, jobType); job.JobDataMap.Add("JobParam", tasksQz.JobParams); ITrigger trigger; #region 泛型传递 //IJobDetail job = JobBuilder.Create<T>() // .WithIdentity(sysSchedule.Name, sysSchedule.JobGroup) // .Build(); #endregion if (tasksQz.Cron != null && CronExpression.IsValidExpression(tasksQz.Cron) && tasksQz.TriggerType > 0) { trigger = CreateCronTrigger(tasksQz); } else { trigger = CreateSimpleTrigger(tasksQz); } // 告诉Quartz使用我们的触发器来安排作业 await _scheduler.Result.ScheduleJob(job, trigger); //await Task.Delay(TimeSpan.FromSeconds(120)); //await Console.Out.WriteLineAsync("关闭了调度器!"); //await _scheduler.Result.Shutdown(); result.success = true; result.msg = $"启动任务:【{tasksQz.Name}】成功"; return(result); } else { result.success = false; result.msg = $"任务计划不存在:【{tasksQz.Name}】"; return(result); } } catch (Exception ex) { throw ex; } }
private void ExistingMessageDownloaded(MessageModel message) { if (message == null) { Messenger.Default.Send<NewMessageEvent>(new NewMessageEvent() { Message = null, IsPush = true }); return; } this.NewMessageCreated(message, true); // If message send was successful, the View should clear the text box // Otherwise, the textbox should not be cleared. Messenger.Default.Send<ExistingMessageEvent>(new ExistingMessageEvent() { Message = message, IsPush = false }); }
/// <summary> /// 编辑信息 /// </summary> /// <param name="userIdentity">0集团,1总店,2分店</param> /// <param name="ShopBelongId">门店所属总店ID</param> /// <param name="model">The model.</param> /// <returns>true if XXXX, false otherwise.</returns> public static bool EditMessage(int userIdentity, int ShopBelongId, MessageModel model) { using (var dal = FactoryDispatcher.MessageFactory()) { if (userIdentity == 2) { model.SendTargetIds = ShopBelongId.ToString(); } if (model.ID > 0) { using (TransactionScope scope = new TransactionScope()) { int messageId = model.ID; var data = dal.GetModel(model.ID); bool flag = dal.UpdateMessageInfo(model); if (flag && model.IsSend == 1 && data.IsSend == 0) { // TODO;添加门店记录 //如果给总后台发布消息通知 if (userIdentity == 1 && model.IsSendBelongShopId == 1) { dal.AddMessageSendTarget(messageId, -1); } if (userIdentity == 1 || userIdentity == 0) { if (model.IsSendBelongShopId == 0 || !string.IsNullOrEmpty(model.SendTargetIds)) { if (string.IsNullOrEmpty(model.SendTargetIds)) { return(false); } string[] targetIds = model.SendTargetIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (targetIds == null || targetIds.Count() == 0) { return(false); } foreach (var targetid in targetIds) { dal.AddMessageSendTarget(messageId, Convert.ToInt32(targetid)); } } } else { dal.AddMessageSendTarget(messageId, ShopBelongId); } } scope.Complete(); return(true); } } else { using (TransactionScope scope = new TransactionScope()) { int messageId = dal.AddMessageInfo(model); if (messageId > 0 && model.IsSend == 1) { // TODO;添加门店记录 //如果给总后台发布消息通知 if (userIdentity == 1 && model.IsSendBelongShopId == 1) { dal.AddMessageSendTarget(messageId, -1); } if (userIdentity == 1 || userIdentity == 0) { if (model.IsSendBelongShopId == 0 || !string.IsNullOrEmpty(model.SendTargetIds)) { if (string.IsNullOrEmpty(model.SendTargetIds)) { return(false); } string[] targetIds = model.SendTargetIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (targetIds == null || targetIds.Count() == 0) { return(false); } foreach (var targetid in targetIds) { dal.AddMessageSendTarget(messageId, Convert.ToInt32(targetid)); } } } else { dal.AddMessageSendTarget(messageId, ShopBelongId); } } scope.Complete(); return(true); } } } }
public void DeleteMessage(MessageModel m) { lock (this) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::DeleteMessage", "start")); this.dataContext.DeleteOnSubmit<MessageModel>(m); this.dataContext.SubmitChanges(); } }
/// <summary> /// Attach file /// </summary> /// <param name="fileSelect"></param> /// <param name="DocumentName"></param> /// <param name="k"></param> /// <returns></returns> public ActionResult CTS230_AttachFile(HttpPostedFileBase fileSelect, string DocumentName, string k) { ICommonHandler commonhandler = ServiceContainer.GetService <ICommonHandler>() as ICommonHandler; MessageModel outmsg = null; try { byte[] fileData; if (fileSelect == null) { outmsg = MessageUtil.GetMessage(MessageUtil.MODULE_COMMON, MessageUtil.MessageList.MSG0050, null); } else { using (BinaryReader reader = new BinaryReader(fileSelect.InputStream)) { var fList = commonhandler.GetAttachFileForGridView(GetCurrentKey()); var filterDupItem = from a in fList where a.FileName.ToUpper().Equals(DocumentName.ToUpper() + Path.GetExtension(fileSelect.FileName).ToUpper()) select a; if (filterDupItem.Count() > 0) { // Docname duplicate outmsg = MessageUtil.GetMessage(MessageUtil.MODULE_COMMON, MessageUtil.MessageList.MSG0115, new string[] { DocumentName }); } else if (DocumentName == null || DocumentName == "") { string nparam = CommonUtil.GetLabelFromResource(MessageUtil.MODULE_CONTRACT, "CTS300", "lblDocumentName"); outmsg = MessageUtil.GetMessage(MessageUtil.MODULE_COMMON, MessageUtil.MessageList.MSG0007, new string[] { nparam }); } else { fileData = reader.ReadBytes(fileSelect.ContentLength); if (commonhandler.CanAttachFile(DocumentName, fileData.Length, Path.GetExtension(fileSelect.FileName), GetCurrentKey(), GetCurrentKey())) { DateTime currDate = DateTime.Now; commonhandler.InsertAttachFile(GetCurrentKey() , DocumentName , Path.GetExtension(fileSelect.FileName) , fileData.Length , fileData , false); } } } } } catch (Exception ex) { outmsg = new MessageModel(); outmsg.Message = ((SECOM_AJIS.Common.Models.ApplicationErrorException)(ex)).ErrorResult.Message.Message; outmsg.Code = CommonValue.SYSTEM_MESSAGE_CODE; } if (outmsg != null) { ViewBag.Message = outmsg.Message; ViewBag.MsgCode = outmsg.Code; } ViewBag.K = k; return(View("CTS230_Upload")); }
private void SaveSingleMessage(MessageModel message, List<UserModel> users, IDataContextWrapper context = null) { if (context == null) { context = this.dataContext; } lock (this) { try { if (message.IsImage) { this.WriteImageToIsoStorage(message.MessageId, message.Image); } // Add the sender/recipient if they are not inthe contact list already if (!this.ContainsContact(message.Sender) && !users.Contains(message.Sender)) { this.AddContact(message.Sender, users); users.Add(message.Sender); } if (!this.ContainsContact(message.Recipient) && !users.Contains(message.Recipient)) { this.AddContact(message.Recipient, users); users.Add(message.Recipient); } this.UpdateConversation(message, context); Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "end find existing conversation")); Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start find existing message")); // If the message already exists, delete it and reinsert it // The reason is that the server version is more authoritative. IQueryable<MessageModel> existingMessages = from m in context.Table<MessageModel>() where (m.ConversationId == message.ConversationId && m.MessageId == message.MessageId) || (m.ClientMessageId == message.ClientMessageId && m.MessageId == Guid.Empty) select m; // Delete the message only if it's a quick send message // otherwise update it MessageModel existingMessage = existingMessages.FirstOrDefault<MessageModel>(); if (existingMessage != null && existingMessage.MessageId == Guid.Empty) { message.LastReadTime = existingMessage.LastReadTime; if (message.IsPollMessage) { message.MyPollResponse = existingMessage.MyPollResponse; } message.ClientVisibleTimeTicks = existingMessage.ClientVisibleTimeTicks; context.DeleteOnSubmit(existingMessage); existingMessage = null; } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "end find existing message")); // Insert it only if the existing message is null if (existingMessage == null) { context.InsertOnSubmit<MessageModel>(message); } context.SubmitChanges(); } catch (Exception ex) { this.dataContext.Dispose(); this.dataContext = new DataContextWrapper<YapperDataContext>(); } } }
public ActionResult SayHelloToSomebody(MessageModel elModelo) { return(View("ShowMessageFromSomebody", elModelo)); }
private void ShowToast(MessageModel message) { ToastPrompt toast = new ToastPrompt(); toast.Title = message.Sender.Name; //toast.ImageSource = this.GetUser(message.Sender.Id).ContactPhoto; toast.HorizontalContentAlignment = HorizontalAlignment.Center; toast.Message = message.IsTaskMessage.Value ? string.Format(Strings.UpdatedTask, message.TaskName) : message.TextMessage; toast.FontSize = 25; toast.Height = 70; toast.Show(); toast.VerticalAlignment = VerticalAlignment.Top; }
private MessageModelSelectedForGeneration(MessageModel message, Message predecessorMessage) : base(predecessorMessage) { Message = message; }
private void btnMessage_Click(object sender, RoutedEventArgs e) { DataContext = new MessageModel(); }
public void AddMessage( string message, string channelName, string poster, MessageType messageType = MessageType.Normal) { var sender = characterManager.Find(poster == Constants.Arguments.ThisCharacter ? model.CurrentCharacter.Name : poster); var channel = model.CurrentChannels.FirstByIdOrNull(channelName) ?? (ChannelModel) model.CurrentPms.FirstByIdOrNull(channelName); if (channel == null) return; // exception circumstance, swallow message Dispatcher.Invoke( (Action) delegate { var thisMessage = new MessageModel(sender, message, messageType); channel.AddMessage(thisMessage, characterManager.IsOfInterest(poster)); if (channel.Settings.LoggingEnabled && ApplicationSettings.AllowLogging) { // check if the user wants logging for this channel logger.LogMessage(channel.Title, channel.Id, thisMessage); } if (poster == Constants.Arguments.ThisCharacter) return; // don't push events for our own messages if (channel is GeneralChannelModel) { events.GetEvent<NewMessageEvent>() .Publish( new Dictionary<string, object> { {Constants.Arguments.Message, thisMessage}, {Constants.Arguments.Channel, channel} }); } else events.GetEvent<NewPmEvent>().Publish(thisMessage); }); }
public static MessageModelSelectedForGeneration Decorate(ModelSelectedForGeneration message, MessageModel model) { return(new(model, message)); }
/// <summary> /// Send new message /// </summary> public MessageModel CreateTask(MessageModel message) { if (!message.IsTaskMessage.Value && !message.IsTaskItemMessage) { return null; } using (DataContextWrapper<YapperDataContext> context = new DataContextWrapper<YapperDataContext>()) { context.Table<MessageModel>().InsertOnSubmit(message); context.SubmitChanges(); Messenger.Default.Send<NewTaskSavedEvent>(new NewTaskSavedEvent() { Task = message }); return message; } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { MessageModel msg = value as MessageModel; if (msg != null) { switch (msg.MsgType) { case MessageType.img: IMClient.Helper.MessageHelper.LoadImgContent(msg, true); return(msg); case MessageType.smallvideo: case MessageType.video: //IMClient.Helper.MessageHelper.LoadVideoPreviewImage(msg); return(msg); case MessageType.file: //msg.FileImg = IMAssets.ImageDeal.DefaultDownloadImg; //IMClient.Helper.MessageHelper.LoadFileContent(msg); if (!msg.IsSending) { string fullName = msg.ResourceModel.FullName; //if (!File.Exists(fullName)) //{ // fullName = Path.Combine(SDKClient.SDKClient.Instance.property.CurrentAccount.filePath, msg.ResourceModel.FileName); //} msg.Content = fullName; } break; default: IMClient.Helper.MessageHelper.ContentInlines = null; return(IMClient.Helper.MessageHelper.GetRichContent(msg.Content, msg.IsMine)); ////var inlines= IMClient.Helper.MessageHelper.GetRichContent(msg.Content); ////if (inlines == null) ////{ //// return new TextBox() { Text = msg.Content, Style = parameter as Style, TextWrapping = TextWrapping.Wrap }; ////} ////else ////{ //// RichTextBox rict = new RichTextBox() { Style = parameter as Style, AcceptsReturn = true }; //// Paragraph parph = new Paragraph(); //// parph.Inlines.AddRange(inlines); //// rict.Document.Blocks.Add(parph); //// return rict; ////} //RichTextBox rict = new RichTextBox() { Style = parameter as Style, }; //IMClient.Helper.MessageHelper.AppendContentToRichTextBox(rict, msg.Content); //return rict; } } return(null); }
private void NewMessageCreated(MessageModel encryptedMessage, bool isPush) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::NewMessageCreated", "start")); (Application.Current as App).PerfTrackerString += "\nInsert to DB:" + (Application.Current as App).PerfTrackerStopWatch.ElapsedMilliseconds.ToString(); if (encryptedMessage == null) { Messenger.Default.Send<NewMessageEvent>(new NewMessageEvent() { Message = null, IsPush = isPush }); return; } MessageModel message = null; try { message = encryptedMessage.DecryptMessage(); } catch (Exception) { message = null; } if (message == null) { Messenger.Default.Send<NewMessageEvent>(new NewMessageEvent() { Message = null, IsPush = isPush }); return; } message.LastReadTime = new DateTime(1970, 1, 1); encryptedMessage.CopyNonEncryptedProperties(message); if (message.IsPollResponseMessage) { this.SavePollResponse(message); } else if (message.IsTaskMessage.Value) { this.SaveSingleTaskMessage(message, new List<UserModel>()); } else { this.SaveSingleMessage(message, new List<UserModel>()); } // Set the last sync time on the server so the tile count is correct when the // server gets a new notification. This is computed based on the last sync time on the // server. YapperServiceProxy.Instance.SetLastSyncDateTime(message.PostDateTime); (Application.Current as App).PerfTrackerString += "\nRefresh ui:" + (Application.Current as App).PerfTrackerStopWatch.ElapsedMilliseconds.ToString(); // If message send was successful, the View should clear the text box // Otherwise, the textbox should not be cleared. Messenger.Default.Send<NewMessageEvent>(new NewMessageEvent() { Message = message, IsPush = isPush }); if (isPush) { // Vibrate the phone Deployment.Current.Dispatcher.BeginInvoke( () => { this.ShowToast(message); this.VibratePhone(); }); } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::NewMessageCreated", "end")); }
private void ChatWindow_SendMessageEvent(UserInfoModel userInfoModel, MessageModel messageModel) { messageList.Where(o => o.Item1 == userInfoModel)?.First().Item2.Add(messageModel); }
private void SavePollResponse(MessageModel message, IDataContextWrapper context = null) { if (context == null) { context = this.dataContext; } lock (this) { try { // If this is a poll response message, update the last update time for the poll message if (message.IsPollResponseMessage && message.IsMine && message.PollMessageId.HasValue) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start update my poll response")); MessageModel pollMessage = this.GetMessage(message.PollMessageId.Value); if (pollMessage != null && pollMessage.LastUpdateTime < message.LastUpdateTime) { pollMessage.LastUpdateTime = message.LastUpdateTime; } if (pollMessage != null) { pollMessage.MyPollResponse = message.PollResponse; } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start update my poll response")); } if (message.IsPollResponseMessage && !message.IsGroup && !message.IsMine && message.PollMessageId.HasValue) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start update other poll response")); MessageModel pollMessage = this.GetMessage(message.PollMessageId.Value); if (pollMessage != null && pollMessage.LastUpdateTime < message.LastUpdateTime) { pollMessage.LastUpdateTime = message.LastUpdateTime; } if (pollMessage != null) { pollMessage.OtherPollResponse = message.PollResponse; } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start update other poll response")); } this.UpdateConversation(message, context); var existingMessages = from m in context.Table<MessageModel>() where (m.ConversationId == message.ConversationId && m.MessageId == message.MessageId) || (m.ConversationId == message.ConversationId && m.ClientMessageId == message.ClientMessageId && m.MessageId == Guid.Empty) select m; // Delete the message only if it's a quick send message // otherwise update it MessageModel existingMessage = existingMessages.FirstOrDefault<MessageModel>(); if (existingMessage != null && existingMessage.MessageId == Guid.Empty) { message.LastReadTime = existingMessage.LastReadTime; message.ClientVisibleTimeTicks = existingMessage.ClientVisibleTimeTicks; context.DeleteOnSubmit(existingMessage); existingMessage = null; } if (existingMessage == null) { context.InsertOnSubmit<MessageModel>(message); } context.SubmitChanges(); } catch (Exception ex) { this.dataContext.Dispose(); this.dataContext = new DataContextWrapper<YapperDataContext>(); } } }
public async Task <MessageModel <NavigationBar> > GetNavigationBar(int uid) { var data = new MessageModel <NavigationBar>(); var uidInHttpcontext1 = 0; var roleIds = new List <int>(); // ids4和jwt切换 if (Permissions.IsUseIds4) { // ids4 uidInHttpcontext1 = (from item in _httpContext.HttpContext.User.Claims where item.Type == "sub" select item.Value).FirstOrDefault().ObjToInt(); roleIds = (from item in _httpContext.HttpContext.User.Claims where item.Type == "role" select item.Value.ObjToInt()).ToList(); } else { // jwt uidInHttpcontext1 = ((JwtHelper.SerializeJwt(_httpContext.HttpContext.Request.Headers["Authorization"].ObjToString().Replace("Bearer ", "")))?.Uid).ObjToInt(); roleIds = (await _userRoleServices.Query(d => d.IsDeleted == false && d.UserId == uid)).Select(d => d.RoleId.ObjToInt()).Distinct().ToList(); } if (uid > 0 && uid == uidInHttpcontext1) { if (roleIds.Any()) { var pids = (await _roleModulePermissionServices.Query(d => d.IsDeleted == false && roleIds.Contains(d.RoleId))).Select(d => d.PermissionId.ObjToInt()).Distinct(); if (pids.Any()) { var rolePermissionMoudles = (await _permissionServices.Query(d => pids.Contains(d.Id))).OrderBy(c => c.OrderSort); var permissionTrees = (from child in rolePermissionMoudles where child.IsDeleted == false orderby child.Id select new NavigationBar { id = child.Id, name = child.Name, pid = child.Pid, order = child.OrderSort, path = child.Code, iconCls = child.Icon, Func = child.Func, IsHide = child.IsHide.ObjToBool(), IsButton = child.IsButton.ObjToBool(), meta = new NavigationBarMeta { requireAuth = true, title = child.Name, NoTabPage = child.IsHide.ObjToBool(), keepAlive = child.IskeepAlive.ObjToBool() } }).ToList(); NavigationBar rootRoot = new NavigationBar() { id = 0, pid = 0, order = 0, name = "根节点", path = "", iconCls = "", meta = new NavigationBarMeta(), }; permissionTrees = permissionTrees.OrderBy(d => d.order).ToList(); RecursionHelper.LoopNaviBarAppendChildren(permissionTrees, rootRoot); data.success = true; if (data.success) { data.response = rootRoot; data.msg = "获取成功"; } } } } return(data); }
private void SaveSingleTaskMessage(MessageModel message, List<UserModel> users, IDataContextWrapper context = null) { if (context == null) { context = this.dataContext; } MessageModel taskInfoMessage = null; lock (this) { try { if (!message.IsTaskMessage.Value) { return; } // Add the sender/recipient if they are not inthe contact list already if (!this.ContainsContact(message.Sender) && !users.Contains(message.Sender)) { this.AddContact(message.Sender, users); users.Add(message.Sender); } if (!this.ContainsContact(message.Recipient) && !users.Contains(message.Recipient)) { this.AddContact(message.Recipient, users); users.Add(message.Recipient); } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "end find existing conversation")); Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start find existing message")); // Task exists // Task exists and deleted // Task doesn't exist // If the message already exists, delete it and reinsert it // The reason is that the server version is more authoritative. IQueryable<MessageModel> existingInfoMessageQuery = from m in context.Table<MessageModel>() where (m.TaskId == message.ClientMessageId) select m; taskInfoMessage = existingInfoMessageQuery.FirstOrDefault<MessageModel>(); bool shouldInsertTaskInfoMessage = false; if (taskInfoMessage == null) { shouldInsertTaskInfoMessage = true; taskInfoMessage = new MessageModel(); taskInfoMessage.ConversationId = message.ConversationId; taskInfoMessage.MessageId = message.MessageId; taskInfoMessage.ClientMessageId = Guid.NewGuid(); taskInfoMessage.Sender = message.Sender; taskInfoMessage.Recipient = message.Recipient; taskInfoMessage.SenderId = taskInfoMessage.Sender.Id; taskInfoMessage.RecipientId = taskInfoMessage.Recipient.Id; taskInfoMessage.MessageType = MessageType.Message; taskInfoMessage.MessageFlags = MessageFlags.TaskInfo; taskInfoMessage.TaskId = message.ClientMessageId; } taskInfoMessage.PostDateTimeUtcTicks = message.PostDateTimeUtcTicks; taskInfoMessage.ClientVisibleTimeTicks = DateTime.UtcNow.Ticks; taskInfoMessage.LastReadTime = new DateTime(1970, 1, 1); taskInfoMessage.LastUpdateTime = DateTime.Now; // If the message already exists, delete it and reinsert it // The reason is that the server version is more authoritative. IQueryable<MessageModel> existingMessages = from m in context.Table<MessageModel>() where (m.ClientMessageId == message.ClientMessageId) select m; MessageModel existingMessage = existingMessages.FirstOrDefault<MessageModel>(); if (existingMessage != null && (!message.IsTaskDeleted.HasValue || !message.IsTaskDeleted.Value)) { if (existingMessage.PostDateTimeUtcTicks > message.PostDateTimeUtcTicks) { return; } existingMessage.PostDateTimeUtcTicks = message.PostDateTimeUtcTicks - 1; if (message.Sender.Id != this.userSettings.Me.Id) { existingMessage.ClientVisibleTimeTicks = DateTime.UtcNow.Ticks; } if (message.Sender.Id == this.userSettings.Me.Id) { existingMessage.LastReadTime = (new DateTime(message.PostDateTimeUtcTicks, DateTimeKind.Utc)).ToLocalTime(); } existingMessage.TaskName = message.TaskName; //existingMessage.IsCompleted = message.IsCompleted; if (existingMessage.RecipientId == 0) { existingMessage.RecipientId = message.RecipientId; } existingMessage.LastTaskUpdaterId = message.SenderId; taskInfoMessage.TextMessage = taskInfoMessage.SenderId == UserSettingsModel.Instance.Me.Id ? string.Format(Strings.YouUpdatedTask, message.TaskName, message.Sender.Name) : string.Format(Strings.HasUpdatedTask, message.Sender.Name, message.TaskName); foreach (var m in message.TaskItemList) { IQueryable<MessageModel> existingTaskItemQuery = from item in context.Table<MessageModel>() where (item.ClientMessageId == m.ClientMessageId) select item; MessageModel existingTaskItem = existingTaskItemQuery.FirstOrDefault<MessageModel>(); if (m.IsTaskDeleted.HasValue && m.IsTaskDeleted.Value) { if (existingTaskItem != null) { context.DeleteOnSubmit<MessageModel>(existingTaskItem); } continue; } if (existingTaskItem == null) { m.LastReadTime = new DateTime(1970, 1, 1); m.PollMessageId = message.ClientMessageId; m.MessageType = MessageType.Message; context.InsertOnSubmit<MessageModel>(m); continue; } existingTaskItem.ClientVisibleTimeTicks = DateTime.UtcNow.Ticks; if (0 != string.Compare(existingTaskItem.TaskName, m.TaskName, StringComparison.OrdinalIgnoreCase) || existingTaskItem.IsCompleted != m.IsCompleted) { existingTaskItem.TaskName = m.TaskName; existingTaskItem.IsCompleted = m.IsCompleted; existingTaskItem.LastTaskUpdaterId = message.SenderId; } if (0 != StringComparer.OrdinalIgnoreCase.Compare(existingTaskItem.ItemOrder, m.ItemOrder)) { existingTaskItem.ItemOrder = m.ItemOrder; } } } else if (existingMessage != null) { if (existingMessage.TaskItemList != null) { foreach (var m in existingMessage.TaskItemList) { context.Attach<MessageModel>(m); context.DeleteOnSubmit<MessageModel>(m); } } context.DeleteOnSubmit<MessageModel>(existingMessage); taskInfoMessage.TextMessage = taskInfoMessage.SenderId == UserSettingsModel.Instance.Me.Id ? string.Format(Strings.YouDeletedTask, message.TaskName, message.Sender.Name) : string.Format(Strings.HasDeletedTask, message.Sender.Name, existingMessage.TaskName, message.TaskName); } else if (existingMessage == null && message.IsTaskDeleted.HasValue && message.IsTaskDeleted.Value) { taskInfoMessage.TextMessage = taskInfoMessage.SenderId == UserSettingsModel.Instance.Me.Id ? string.Format(Strings.YouDeletedTask, message.TaskName, message.Sender.Name) : string.Format(Strings.HasDeletedTask, message.Sender.Name, existingMessage.TaskName, message.TaskName); } else if (existingMessage == null && (!message.IsTaskDeleted.HasValue || !message.IsTaskDeleted.Value)) { message.ClientVisibleTimeTicks = DateTime.UtcNow.Ticks; message.ConversationId = Guid.Empty; message.MessageId = Guid.NewGuid(); message.LastReadTime = new DateTime(1970, 1, 1); context.InsertOnSubmit<MessageModel>(message); if (message.TaskItemList != null) { foreach (var m in message.TaskItemList) { if (m.ClientMessageId != Guid.Parse("bbaf9b96-b875-4a23-97ac-77912ca74832")) { m.LastReadTime = new DateTime(1970, 1, 1); context.InsertOnSubmit<MessageModel>(m); } } } taskInfoMessage.TextMessage = taskInfoMessage.SenderId == UserSettingsModel.Instance.Me.Id ? string.Format(Strings.YouSharedTask, message.TaskName, message.Sender.Name) : string.Format(Strings.HasSharedTask, message.Sender.Name, message.TaskName); } if (shouldInsertTaskInfoMessage) { //context.InsertOnSubmit<MessageModel>(taskInfoMessage); //this.UpdateConversation(taskInfoMessage, context); } Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "end find existing message")); context.SubmitChanges(); } catch (Exception ex) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "Error in DataSync::SaveSingleTaskMessage for task ", message.TaskName)); this.dataContext.Dispose(); this.dataContext = new DataContextWrapper<YapperDataContext>(); } } Messenger.Default.Send<NewMessageEvent>(new NewMessageEvent() { Message = taskInfoMessage, IsPush = false }); }
public TwilioModel SendSms(SmsModel sms) { //#if DEBUG // var message = new // { // Sid = "debugging" // }; //#else var message = MessageResource.Create( to: new PhoneNumber(sms.SentTo), from: new PhoneNumber(sms.FromNumber), body: sms.Subject + " " + sms.Body + " " + DateTime.Now.ToShortDateString(), client: _client); // pass in the custom client //#endif if (!string.IsNullOrEmpty(message.Sid)) { var messageModel = new MessageModel { MessageId = Guid.NewGuid(), MessageType = sms.Subject, MessageBody = sms.Body + " " + DateTime.Now.ToShortDateString() }; var smsModel = new SmsModel { SMSId = Guid.NewGuid(), Subject = sms.Subject + "Id:" + message.Sid + "_" + Guid.NewGuid().ToString().Substring(5, 9), SentTo = sms.SentTo, Body = sms.Body + " " + DateTime.Now.ToShortDateString(), FromNumber = sms.FromNumber, StatusId = 1 }; var errors = string.Empty; var saveMessage = _messageService.SaveMessage(messageModel); var saveSms = _smsService.SaveSms(smsModel); if (string.IsNullOrEmpty(saveMessage)) { errors += "message not saved ."; } if (string.IsNullOrEmpty(saveSms)) { errors += "sms not saved ."; } return(new TwilioModel { StatusCode = SmsEnum.SuccessMessage.ToString(), SuccessId = message.Sid + "_" + Guid.NewGuid().ToString().Substring(5, 9), Error = errors }); } return(new TwilioModel { StatusCode = SmsEnum.ErrorMessage.ToString(), SuccessId = Guid.NewGuid().ToString().Substring(5, 9), Error = SmsEnum.ErrorMessage.GetDescription() }); }
private void UpdateConversation(MessageModel message, IDataContextWrapper context) { // Update the conversation object corresponding to the message MessageModel existingConversation = null; IQueryable<MessageModel> existingConversationIQueryable = null; Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::MessagesDownloaded", "start find existing conversation")); if (message.ConversationId != Guid.Empty && existingConversation == null) { existingConversationIQueryable = from m in context.Table<MessageModel>() where m.ConversationId == message.ConversationId && m.MessageType == MessageType.Conversation select m; existingConversation = existingConversationIQueryable.FirstOrDefault<MessageModel>(); if (existingConversation != null) { if (existingConversation.LastUpdateTime < message.LastUpdateTime) { existingConversation.LastUpdateTime = message.LastUpdateTime; existingConversation.TextMessage = message.TextMessage; } if (existingConversation.LastReadTime.Ticks < message.LastUpdateTime.Ticks) { if (!existingConversation.UnreadCount.HasValue || message.Sender.Id == this.userSettings.Me.Id) { existingConversation.UnreadCount = 0; } else { existingConversation.UnreadCount = existingConversation.UnreadCount.Value + 1; } } } else { existingConversation = new MessageModel(message); existingConversation.MessageId = Guid.Empty; existingConversation.ClientMessageId = Guid.Empty; existingConversation.MessageType = MessageType.Conversation; existingConversation.MessageFlags = 0; existingConversation.Image = null; existingConversation.LastUpdateTime = message.LastUpdateTime; existingConversation.TextMessage = message.TextMessage; existingConversation.LastReadTime = new DateTime(1970, 1, 1); existingConversation.UnreadCount = 1; context.InsertOnSubmit<MessageModel>(existingConversation); } } }
/// <summary> /// 发送消息到指定组 /// </summary> /// <param name="groupName"></param> /// <param name="message"></param> public void SendToGroup(MessageModel msg) { _hubContext.Clients.Group(msg.GroupName).recieveMessage(msg); }
public void InsertMessageToDBBeforeSending(MessageModel message) { lock (this) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::InsertMessageToDBBeforeSending", "start")); if (message.IsImage) { this.WriteImageToIsoStorage(message.MessageId, message.Image); } if (message.IsPollResponseMessage) { MessageModel pollMessage = this.GetMessage(message.PollMessageId.Value); pollMessage.MyPollResponse = message.PollResponse; } // Write the message this.dataContext.Table<MessageModel>().InsertOnSubmit(message); this.dataContext.SubmitChanges(); Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync::InsertMessageToDBBeforeSending", "end")); (Application.Current as App).PerfTrackerString += "\nQuick insert:" + (Application.Current as App).PerfTrackerStopWatch.ElapsedMilliseconds.ToString(); } }
public void SendToConnection(MessageModel msg) { _hubContext.Clients.Client(msg.ConnectionID).recieveMessage(msg); }
/// <summary> /// Send new message /// </summary> public void PostPollResponse(MessageModel pollResponse) { if (pollResponse.PollMessageId == Guid.Empty && pollResponse.PollClientMessageId.HasValue && pollResponse.PollClientMessageId.Value == Guid.Empty) { MessageModel m = this.GetMessageFromClientId(pollResponse.PollClientMessageId.Value); if (m != null) { pollResponse.PollMessageId = m.MessageId; } } this.SendMessage(pollResponse); }
public void sendToAll(MessageModel msg) { // Call the broadcastMessage method to update clients. _hubContext.Clients.All.recieveMessage(msg); }
public void SetLastReadTime(MessageModel message) { lock (this) { using (DataContextWrapper<YapperDataContext> context = new DataContextWrapper<YapperDataContext>()) { Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync", "Start update last read time")); context.Attach<MessageModel>(message); message.LastReadTime = DateTime.Now; context.SubmitChanges(); Debug.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt"), "DataSync", "End update last read time")); } } }
/// <summary> /// 接收客户端数据.websocket 从ClientList类里拿。 /// </summary> /// <param name="webSocket">webSocket 对象</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <string> ReceiveDataAsyncDataTableNew(WebSocket webSocket, CancellationToken cancellationToken, MysqlDBContext mysqlcontext) { WebSocketReceiveResult result; MessageModel msg = null; if (webSocket.State != WebSocketState.Open) { return(""); } while (!webSocket.CloseStatus.HasValue) { ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[1024 * 2]); result = await webSocket.ReceiveAsync(buffer, cancellationToken); if (result.MessageType == WebSocketMessageType.Close) { break; } ArraySegment <byte> segment = null; if (result.Count > 0) { try { msg = JsonConvert.DeserializeObject <MessageModel>(Encoding.Default.GetString(buffer)); if (msg == null) { break; } //这个只是发送了部分数据出去。 byte[] newbuf = Encoding.UTF8.GetBytes(msg.Data.ToString());//过度下,按实际大小返回给客户端。 segment = new ArraySegment <byte>(newbuf); ClientList.AddDicUser(msg.RoomId + msg.SenderId, webSocket); MessageModel message = new MessageModel(); //message.Id = 2;//id message.RoomId = msg.RoomId; message.SenderId = msg.SenderId; message.TargetId = msg.TargetId; message.Data = msg.Data; mysqlcontext.Add(message); mysqlcontext.SaveChanges(); } catch (Exception ex) { _logger.LogError(ex.Message); } List <Task> tasks = new List <Task>(); switch (msg.SendType) { //Broadcast all user. case Model.SendType.Broadcast: if (ClientList.userdic.ContainsKey(msg.RoomId)) { ClientList.userdic[msg.RoomId].ForEach(ws => { tasks.Add(ws.SendAsync(segment, result.MessageType, result.EndOfMessage, CancellationToken.None)); }); Task.WaitAll(tasks.ToArray()); } else if (ClientList.userdic.ContainsKey(msg.RoomId + msg.SenderId)) { //added by longdb 2020.6.17 Get offline information。 List <MessageModel> mmodel2 = mysqlcontext.Set <MessageModel>().Where(p => p.SenderId == msg.SenderId).ToList(); ClientList.userdic[msg.RoomId + msg.SenderId].ForEach(ws => { tasks.Add(ws.SendAsync(segment, result.MessageType, result.EndOfMessage, CancellationToken.None)); }); Task.WaitAll(tasks.ToArray()); } break; //one to one. case Model.SendType.Unicast: if (ClientList.userdic.ContainsKey(msg.RoomId) && ClientList.userdic[msg.RoomId].Count > 0) { WebSocket siglews = ClientList.userdic[msg.RoomId].Where(ws => ws == webSocket).FirstOrDefault(); tasks.Add(siglews.SendAsync(segment, result.MessageType, result.EndOfMessage, CancellationToken.None)); Task.WaitAll(tasks.ToArray()); } break; } } } if (msg != null && ClientList.userdic.ContainsKey(msg.RoomId)) { WebSocket socketmodel = ClientList.userdic[msg.RoomId].Where(ws => ws == webSocket).FirstOrDefault(); //移除聊天室中的某个成员 ClientList.RemoveDicUser(msg.RoomId, socketmodel); //关闭当前异常连接。 await socketmodel.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None); } return(""); }
public void SendNewMessage(UserModel sender, UserModel recipient, long conversationId, string message, Action<YapperChat.Models.MessageModel> callback) { MessageModel messageModel = null; if (!this.SimulateSendMessageFailure) { messageModel = new MessageModel(); messageModel.ConversationId = conversationId; messageModel.TextMessage = message; messageModel.Sender = sender; messageModel.Recipient = recipient; messageModel.MessageId = (new Random((int)DateTime.Now.Ticks).Next(1000, 2000)); messageModel.PostDateTime = DateTime.UtcNow; } callback(messageModel); }
/// <summary> /// 接收客户端数据.websocket 从ClientList类里拿。 /// </summary> /// <param name="webSocket">webSocket 对象</param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <string> ReceiveDataAsyncNew(WebSocket webSocket, CancellationToken cancellationToken) { WebSocketReceiveResult result; MessageModel msg = null; if (webSocket.State != WebSocketState.Open) { return(""); } while (!webSocket.CloseStatus.HasValue) { ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[1024 * 2]); result = await webSocket.ReceiveAsync(buffer, cancellationToken); if (result.MessageType == WebSocketMessageType.Close) { break; } if (result.Count > 0) { msg = JsonConvert.DeserializeObject <MessageModel>(Encoding.Default.GetString(buffer)); if (msg == null) { break; } #region 所有数据发送出去 //using MemoryStream ms = new MemoryStream();//新语法。 //ms.Write(buffer.Array, buffer.Offset, result.Count - buffer.Offset); //ms.Seek(0, SeekOrigin.Begin); //var reader = new StreamReader(ms); //var message = reader.ReadToEnd(); //reader.Dispose(); #endregion //这个只是发送了部分数据出去。 byte[] newbuf = Encoding.UTF8.GetBytes(msg.Data.ToString());//过度下,按实际大小返回给客户端。 var segment = new ArraySegment <byte>(newbuf); ClientList.AddDicUser(msg.RoomId, webSocket); List <Task> tasks = new List <Task>(); switch (msg.SendType) { //Broadcast all user. case Model.SendType.Broadcast: if (ClientList.userdic.ContainsKey(msg.RoomId)) { ClientList.userdic[msg.RoomId].ForEach(ws => { tasks.Add(ws.SendAsync(segment, result.MessageType, result.EndOfMessage, CancellationToken.None)); }); Task.WaitAll(tasks.ToArray()); } break; //one to one. case Model.SendType.Unicast: if (ClientList.userdic.ContainsKey(msg.RoomId) && ClientList.userdic[msg.RoomId].Count > 0) { WebSocket siglews = ClientList.userdic[msg.RoomId].Where(ws => ws == webSocket).FirstOrDefault(); tasks.Add(siglews.SendAsync(segment, result.MessageType, result.EndOfMessage, CancellationToken.None)); Task.WaitAll(tasks.ToArray()); } break; } } } if (msg != null && ClientList.userdic.ContainsKey(msg.RoomId)) { WebSocket socketmodel = ClientList.userdic[msg.RoomId].Where(ws => ws == webSocket).FirstOrDefault(); //移除聊天室中的某个成员 ClientList.RemoveDicUser(msg.RoomId, socketmodel); //关闭当前异常连接。 await socketmodel.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None); } return(""); }