private void GoToNotification(NotificationModel x) { var subject = x.Subject.Type.ToLower(); if (subject.Equals("issue")) { ReadCommand.Execute(x); var node = x.Subject.Url.Substring(x.Subject.Url.LastIndexOf('/') + 1); ShowViewModel<IssueViewModel>(new IssueViewModel.NavObject { Username = x.Repository.Owner.Login,Repository = x.Repository.Name, Id = long.Parse(node) }); } else if (subject.Equals("pullrequest")) { ReadCommand.Execute(x); var node = x.Subject.Url.Substring(x.Subject.Url.LastIndexOf('/') + 1); ShowViewModel<PullRequestViewModel>(new PullRequestViewModel.NavObject { Username = x.Repository.Owner.Login, Repository = x.Repository.Name, Id = long.Parse(node) }); } else if (subject.Equals("commit")) { ReadCommand.Execute(x); var node = x.Subject.Url.Substring(x.Subject.Url.LastIndexOf('/') + 1); ShowViewModel<ChangesetViewModel>(new ChangesetViewModel.NavObject { Username = x.Repository.Owner.Login, Repository = x.Repository.Name, Node = node }); } else if (subject.Equals("release")) { ReadCommand.Execute(x); ShowViewModel<BranchesAndTagsViewModel>(new BranchesAndTagsViewModel.NavObject { Username = x.Repository.Owner.Login, Repository = x.Repository.Name, IsShowingBranches = false }); } }
// // GET: /Notification/ public ActionResult Index() { GetFriendRequestsModel gfrm = new GetFriendRequestsModel(); gfrm.UserProfileId = accountServices.GetUserByUsername(User.Identity.Name).UserId; IQueryable<UserProfileModel> iq = accountServices.GetFriendRequests(gfrm); NotificationModel nm = new NotificationModel(); nm.FriendRequestNotifications = new List<FriendRequestViewModel>(); List<UserProfileModel> lupm = iq.ToList<UserProfileModel>(); foreach (UserProfileModel upm in lupm) { FriendRequestViewModel frm = new FriendRequestViewModel(); frm.UserProfileId = upm.UserProfileId; frm.FullName = upm.FirstName + " " + upm.LastName; nm.FriendRequestNotifications.Add(frm); } IQueryable<MessageModel> messageList = EventServices.GetInstance().GetMessages(new GetMessagesModel { GetUnreadOnly = true, UserProfileID = gfrm.UserProfileId }); List<MessageViewModel> messageViewList = new List<MessageViewModel>(); foreach (MessageModel mm in messageList) { UserProfileModel sender = accountServices.GetUserProfileByUserProfileId(mm.SenderProfileID); messageViewList.Add(new MessageViewModel { EventID = mm.EventID != null ? (int)mm.EventID : -1, EventName = EventServices.GetInstance().GetEventById(mm.EventID != null ? (int)mm.EventID : -1).Title, Message = mm.Message, MessageID = mm.MessageID, SenderName = sender.FirstName + " " + sender.LastName, SenderProfileID = mm.SenderProfileID }); } nm.UnreadMessages = messageViewList; return View(nm); }
private void GoToNotification(NotificationModel x) { var subject = x.Subject.Type.ToLower(); if (subject.Equals("issue")) { var node = x.Subject.Url.Substring(x.Subject.Url.LastIndexOf('/') + 1); var vm = CreateViewModel<IssueViewModel>(); vm.RepositoryOwner = x.Repository.Owner.Login; vm.RepositoryName = x.Repository.Name; vm.IssueId = long.Parse(node); ShowViewModel(vm); } else if (subject.Equals("pullrequest")) { var node = x.Subject.Url.Substring(x.Subject.Url.LastIndexOf('/') + 1); var vm = CreateViewModel<PullRequestViewModel>(); vm.RepositoryOwner = x.Repository.Owner.Login; vm.RepositoryName = x.Repository.Name; vm.PullRequestId = long.Parse(node); ShowViewModel(vm); } else if (subject.Equals("commit")) { var node = x.Subject.Url.Substring(x.Subject.Url.LastIndexOf('/') + 1); var vm = CreateViewModel<ChangesetViewModel>(); vm.RepositoryOwner = x.Repository.Owner.Login; vm.RepositoryName = x.Repository.Name; vm.Node = node; ShowViewModel(vm); } else if (subject.Equals("release")) { var vm = CreateViewModel<BranchesAndTagsViewModel>(); vm.RepositoryOwner = x.Repository.Owner.Login; vm.RepositoryName = x.Repository.Name; vm.SelectedFilter = BranchesAndTagsViewModel.ShowIndex.Tags; ShowViewModel(vm); } ReadNotification(x); }
public static void NotifyWithSettings(this IManageToasts toasts, NotificationModel notification, ChannelSettingsModel.NotifyLevel notifyLevel) { switch (notifyLevel) { case ChannelSettingsModel.NotifyLevel.NoNotification: break; case ChannelSettingsModel.NotifyLevel.NotificationOnly: toasts.AddNotification(notification); break; case ChannelSettingsModel.NotifyLevel.NotificationAndToast: toasts.AddNotification(notification); toasts.FlashWindow(); toasts.ShowToast(); break; case ChannelSettingsModel.NotifyLevel.NotificationAndSound: toasts.AddNotification(notification); toasts.FlashWindow(); toasts.PlaySound(); toasts.ShowToast(); break; } }
private void OnNewUpdateEvent(NotificationModel param) { OnPropertyChanged("ConversationWith"); OnPropertyChanged("StatusString"); OnPropertyChanged("HasStatus"); OnPropertyChanged("CanPost"); OnPropertyChanged("TypingString"); var arguments = ((CharacterUpdateModel) param).Arguments; if (!(arguments is CharacterUpdateModel.PromoteDemoteEventArgs)) OnStatusChanged(); }
public static void NewUpdate(this IEventAggregator events, NotificationModel update) => events.GetEvent<NewUpdateEvent>().Publish(update);
public void UpdateModel(NotificationModel notificationModel) { Clients.All.UpdateModel(notificationModel); }
//Update Adjustment public static AdjustmentModel UpdateAdjustment(AdjustmentModel adjm, out string error) { error = ""; LUSSISEntities entities = new LUSSISEntities(); NotificationModel nom = new NotificationModel(); adjustment adj = new adjustment(); try { adj = entities.adjustments.Where(a => a.adjid == adjm.Adjid).First <adjustment>(); adj.raisedby = adjm.Raisedby; adj.raisedto = adjm.Raisedto; adj.issueddate = adjm.Issueddate; adj.status = adjm.Status; nom.Remark = "The Adjustment Voucher has been Rejected!"; if (adj.status == ConAdjustment.Active.APPROVED) { nom.Remark = "The Adjustment Voucher has been Approved!"; } List <AdjustmentDetailModel> adjustds = AdjustmentDetailRepo.GetAdjustmentDetailByAdjID(adj.adjid, out error); foreach (AdjustmentDetailModel adjustd in adjustds) { InventoryModel inventm = InventoryRepo.GetInventoryByItemid(adjustd.Itemid, out error); inventory invent = entities.inventories.Where(i => i.invid == inventm.Invid).First <inventory>(); invent.stock += adjustd.Adjustedqty; InventoryTransactionModel invtm = new InventoryTransactionModel(); invtm.InvID = invent.invid; invtm.ItemID = invent.itemid; invtm.Qty = adjustd.Adjustedqty; invtm.TransType = ConInventoryTransaction.TransType.ADJUSTMENT; invtm.TransDate = DateTime.Now; invtm.Remark = adjustd.Reason; invtm = InventoryTransactionRepo.CreateInventoryTransaction(invtm, out error); } entities.SaveChanges(); adjm = GetAdjustmentByID(adj.adjid, out error); nom.Deptid = DepartmentRepo.GetDepartmentByUserid(adj.raisedto ?? default(int), out error).Deptid; nom.Role = UserRepo.GetUserByUserID(adj.raisedby ?? default(int)).Role; nom.Title = "Adjustment Approval"; nom.NotiType = ConNotification.NotiType.Adjustment; nom.ResID = adj.adjid; nom = NotificationRepo.CreatNotification(nom, out error); } catch (NullReferenceException) { error = ConError.Status.NOTFOUND; } catch (Exception e) { error = e.Message; } return(adjm); }
private void HandleNotification(NotificationModel notification) { // TODO: I'M DYIN' OVER HERE! REFACTOR ME! // character update models will be *most* of the notification the user will see var model = notification as CharacterUpdateModel; if (model != null) { var targetCharacter = model.TargetCharacter.Name; var args = model.Arguments; // handle if the notification involves a character being promoted or demoted var eventArgs = args as CharacterUpdateModel.PromoteDemoteEventArgs; if (eventArgs != null) { var channelId = eventArgs.TargetChannelId; // find by ID, not name var channel = cm.CurrentChannels.FirstByIdOrNull(channelId); if (channel == null) return; if (channel.Settings.PromoteDemoteNotifyOnlyForInteresting) { if (!IsOfInterest(targetCharacter)) return; // if we only want to know interesting people, no need to evalute further } ConvertNotificationLevelToAction( channel.Settings.PromoteDemoteNotifyLevel, channelId, model); } else if (args is CharacterUpdateModel.JoinLeaveEventArgs) { // special check for this as it has settings per channel var target = ((CharacterUpdateModel.JoinLeaveEventArgs) args).TargetChannelId; // find by ID, not name var channel = cm.CurrentChannels.FirstByIdOrNull(target); if (channel == null) return; if (channel.Settings.JoinLeaveNotifyOnlyForInteresting) { if (!IsOfInterest(targetCharacter)) return; } ConvertNotificationLevelToAction(channel.Settings.JoinLeaveNotifyLevel, target, model); } else if (args is CharacterUpdateModel.NoteEventArgs || args is CharacterUpdateModel.CommentEventArgs) { AddNotification(model); var link = args is CharacterUpdateModel.NoteEventArgs ? ((CharacterUpdateModel.NoteEventArgs) args).Link : ((CharacterUpdateModel.CommentEventArgs) args).Link; NotifyUser(false, false, notification.ToString(), link); } else if (args is CharacterUpdateModel.ListChangedEventArgs) { AddNotification(model); NotifyUser(false, false, notification.ToString(), targetCharacter); } else if (args is CharacterUpdateModel.ReportHandledEventArgs) { AddNotification(model); NotifyUser(true, true, notification.ToString(), targetCharacter); } else if (args is CharacterUpdateModel.ReportFiledEventArgs) { AddNotification(model); NotifyUser(true, true, notification.ToString(), targetCharacter, "report"); } else if (args is CharacterUpdateModel.BroadcastEventArgs) { AddNotification(model); NotifyUser(true, true, notification.ToString(), targetCharacter); } else if (IsOfInterest(targetCharacter, false) && !model.TargetCharacter.IgnoreUpdates) { AddNotification(model); if (cm.CurrentChannel is PmChannelModel) { if ((cm.CurrentChannel as PmChannelModel).Id.Equals( targetCharacter, StringComparison.OrdinalIgnoreCase)) return; // don't make a toast if we have their tab focused as it is redundant } NotifyUser(false, false, notification.ToString(), targetCharacter); } } else { var channelUpdate = (ChannelUpdateModel) notification; if (!channelUpdate.TargetChannel.Settings.AlertAboutUpdates) return; AddNotification(notification); NotifyUser(false, false, notification.ToString(), channelUpdate.TargetChannel.Id); } }
private void UpdateRightClickMenu(NotificationModel argument) { if (!RightClickMenuViewModel.IsOpen) return; var updateKind = argument as CharacterUpdateModel; if (updateKind == null) return; if (RightClickMenuViewModel.Target == null) return; if (updateKind.TargetCharacter.Name == RightClickMenuViewModel.Target.Name) OnRightClickMenuUpdated(RightClickMenuViewModel.Target); OnPropertyChanged("RightClickMenuViewModel"); }
private void HandleNotification(NotificationModel notification) { notification.DisplayNewToast(ChatState, ToastManager); }
/// <summary> /// Method doing actually something with the changes obtained via the web hook notification. /// In this demo we're just logging to a list, in your implementation you do what you need to do :-) /// </summary> private static void DoWork(ClientContext approvalCC, List approvalList, ClientContext notificationCC, List notificationSourceList, Change change, NotificationModel notification, TraceWriter log) { try { log.Info("Loading source item with id: " + ((ChangeItem)change).ItemId); log.Info("Notification Source List name:" + notificationSourceList.Title + " " + notificationSourceList.ParentWebUrl); ListItem li = notificationSourceList.GetItemById(((ChangeItem)change).ItemId); notificationCC.Load(li); notificationCC.ExecuteQuery(); log.Info("Loaded source item with ID: " + ((ChangeItem)change).ItemId); // Only add approval item if in PEnding approval status if (li.FieldValues["_ModerationStatus"].ToString() == "2") { var changeItem = change as ChangeItem; CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><And><And>"; camlQuery.ViewXml += $"<Eq><FieldRef Name='ClientState' /><Value Type='Text'>{notification.ClientState}</Value></Eq>"; camlQuery.ViewXml += $"<Eq><FieldRef Name='Resource' /><Value Type='Text'>{notification.Resource}</Value></Eq></And>"; camlQuery.ViewXml += $"<And><Eq><FieldRef Name='ItemId' /><Value Type='Text'>{changeItem.ItemId}</Value></Eq>"; camlQuery.ViewXml += $"<Eq><FieldRef Name='ActivityId' /><Value Type='Text'>{changeItem.UniqueId}</Value></Eq>"; camlQuery.ViewXml += $"</And></And></Where></Query></View>"; ListItemCollection matchingItems = approvalList.GetItems(camlQuery); approvalCC.Load(matchingItems); approvalCC.ExecuteQuery(); if (matchingItems.Count() == 0) { ListItemCreationInformation newItem = new ListItemCreationInformation(); ListItem item = approvalList.AddItem(newItem); var editor = li.FieldValues["Editor"] as FieldUserValue; item["Title"] = string.Format("List {0} had a Change of type \"{1}\" on the item with Id {2}.", notificationSourceList.Title, change.ChangeType.ToString(), (change as ChangeItem).ItemId); item["ClientState"] = notification.ClientState; item["SubscriptionId"] = notification.SubscriptionId; item["ExpirationDateTime"] = notification.ExpirationDateTime; item["Resource"] = notification.Resource; item["TenantId"] = notification.TenantId; item["SiteUrl"] = notification.SiteUrl; item["WebId"] = notification.WebId; item["ItemId"] = changeItem.ItemId; item["ActivityId"] = changeItem.UniqueId; item["EditorEmail"] = editor.Email; item["Activity"] = change.ChangeType.ToString(); item.Update(); approvalCC.ExecuteQueryRetry(); } } } catch (Exception exp) { log.Error("Unable to log approval: " + exp.Message + ":::" + exp.StackTrace); } }
private async Task OperationAckAsync( NotificationModel payload, CancellationToken cancellationToken) { await this.marketplaceProcessor.OperationAckAsync(payload.SubscriptionId, payload.OperationId, payload.PlanId, payload.Quantity, cancellationToken).ConfigureAwait(false); }
public void Save(NotificationModel model) { }
private void UpdateCount(Notification notification, ref NotificationModel model) { var quizzNotification = notification.QuizzNotification; switch (notification.NotificationType) { case NotificationTypeEnum.QuizzLike: break; case NotificationTypeEnum.DepQuizzReceiveComment: case NotificationTypeEnum.QuizzComment: model.Count = _uow.Quizzes.GetAll() .Where(q => q.Id == quizzNotification.QuizzId) .Select(q => q.Comments.Select(c => c.AuthorId).Distinct().Count()) .FirstOrDefault(); break; case NotificationTypeEnum.QuizzTake: model.Count = _uow.QuizLogs.GetAll() .Where(l => l.QuizzId == quizzNotification.QuizzId) .Select(l => l.UserId) .Distinct() .Count(); break; case NotificationTypeEnum.QuestionFlag: break; case NotificationTypeEnum.QuizzCommentLike: break; case NotificationTypeEnum.QuizzCommentFlag: break; case NotificationTypeEnum.DepQuizzSubmit: break; case NotificationTypeEnum.DepQuizzLive: break; case NotificationTypeEnum.DepPostComment: break; case NotificationTypeEnum.DepPostedCommentModified: break; case NotificationTypeEnum.DepPostedCommentFlagged: break; case NotificationTypeEnum.DepQuestionFlagged: break; case NotificationTypeEnum.DepMessageSent: break; case NotificationTypeEnum.DepMessageReceived: break; case NotificationTypeEnum.DepQuizzmateReceiveRequest: break; case NotificationTypeEnum.DepQuizzmateReceiveRequestAccept: break; default: break; } }
private async void SendComment_Clicked(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(viewModel.CommentText) && viewModel.CommentPosts.Any() == false) { await DisplayAlert("", Language.nhap_binh_luan_hoac_chon_tin_dang_de_gui_binh_luan, Language.dong); return; } loadingPopup.IsVisible = true; PostItemComment comment = new PostItemComment(); if (!string.IsNullOrWhiteSpace(viewModel.CommentText)) { comment.HasText = true; comment.Text = viewModel.CommentText.Trim(); } comment.PostItemId = viewModel.PostItem.Id; comment.CreatedDate = DateTime.Now; comment.CreatedById = UserLogged.Id; comment.CreatedBy = new PostItemUser() // them cho nay de giao dien co. ko luu db. { UserId = UserLogged.Id, FullName = UserLogged.FullName, Avatar = UserLogged.AvatarUrl // neu la lnk full thi avatar full url tra ve nguyen ven. }; if (viewModel.CommentPosts.Any()) { comment.HasPost = true; comment.Posts = viewModel.CommentPosts.ToList(); } viewModel.InsertComment(comment); viewModel.Comments.Insert(0, comment); CancelCommnet_Clicked(sender, EventArgs.Empty); EditorComment.Unfocus(); loadingPopup.IsVisible = false; try { INotificationService notificationService = DependencyService.Get <INotificationService>(); var AllUserReceiveNoti = await viewModel._postItemService.GetReceiveNotificationUser(viewModel.PostItem.Id); //var allUserFollow = string[] CommentUserIds = AllUserReceiveNoti.Where(x => x != UserLogged.Id).ToArray(); string NotificationTitle = UserLogged.FullName + " " + Language.da_binh_luan_trong_bai_viet; string NotificationImage = (viewModel.PostItem.Images != null && viewModel.PostItem.Images.Length > 0) ? AvatarHelper.GetPostAvatar(viewModel.PostItem.Images.FirstOrDefault()) : ""; foreach (var userIdComment in CommentUserIds) { Guid ReceiverId = Guid.Parse(userIdComment); NotificationModel notification = new NotificationModel() { UserId = ReceiverId, CurrentBadgeCount = (int)notificationService.CountNotReadNotificationUser(ReceiverId) + 1, Title = NotificationTitle, NotificationType = NotificationType.ViewPostItem, PostItemId = viewModel.PostItem.Id, CreatedDate = DateTime.Now, IsRead = false, Thumbnail = NotificationImage }; await notificationService.AddNotification(notification, Language.binh_luan); } } catch (Exception ex) { //await DisplayAlert("", "Có lỗi khi gửi thông báo!", Language.dong); } }
public static void ProcessNotification(ILogger log, string queueItem) { NotificationModel notification = JsonConvert.DeserializeObject <NotificationModel>(queueItem); log.LogInformation($"Processing notification: {notification.Resource}"); #region Get Context string url = string.Format($"https://{CloudConfigurationManager.GetSetting("SP_Tenant_Name")}.sharepoint.com{notification.SiteUrl}"); OfficeDevPnP.Core.AuthenticationManager am = new AuthenticationManager(); ClientContext cc = am.GetAppOnlyAuthenticatedContext( url, CloudConfigurationManager.GetSetting("SPApp_ClientId"), CloudConfigurationManager.GetSetting("SPApp_ClientSecret")); #endregion #region Grab the list for which the web hook was triggered List changeList = cc.Web.GetListById(new Guid(notification.Resource)); cc.ExecuteQueryRetry(); if (changeList == null) { // list has been deleted in between the event being fired and the event being processed log.LogInformation($"List \"{notification.Resource}\" no longer exists."); return; } #endregion #region Get the Last Change Token from the Azure table CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("AzureWebJobsStorage")); CloudTableClient client = storageAccount.CreateCloudTableClient(); CloudTable table = client.GetTableReference(CloudConfigurationManager.GetSetting("LastChangeTokensTableName")); table.CreateIfNotExists(); TableOperation retrieveOperation = TableOperation.Retrieve <LastChangeEntity>("LastChangeToken", notification.Resource); TableResult query = table.Execute(retrieveOperation); ChangeToken lastChangeToken = null; if (query.Result != null) { lastChangeToken = new ChangeToken() { StringValue = ((LastChangeEntity)query.Result).LastChangeToken }; } if (lastChangeToken == null) { lastChangeToken = new ChangeToken() { StringValue = $"1;3;{notification.Resource};{DateTime.Now.AddMinutes(-60).ToUniversalTime().Ticks.ToString()};-1" }; } #endregion #region Grab Changes since Last Change Token (in batches) ChangeQuery changeQuery = new ChangeQuery(false, true) { Item = true, FetchLimit = 1000 // Max value is 2000, default = 1000 }; //List will keep track of items we have already handled List <int> handledListItems = new List <int>(); // Start pulling down the changes bool allChangesRead = false; do { //Assign the change token to the query...this determines from what point in time we'll receive changes changeQuery.ChangeTokenStart = lastChangeToken; ChangeCollection changes = changeList.GetChanges(changeQuery); cc.Load(changes); cc.ExecuteQueryRetry(); #endregion // Save last used changetoken to Azure table. We'll start from that one when the next event hits our service if (changes.Count > 0) { foreach (Change change in changes) { lastChangeToken = change.ChangeToken; } } LastChangeEntity lce = new LastChangeEntity("LastChangeToken", notification.Resource) { LastChangeToken = lastChangeToken.StringValue }; TableOperation insertOperation = TableOperation.InsertOrReplace(lce); table.Execute(insertOperation); #region Process changes log.LogInformation($"Changes found: {changes.Count}"); if (changes.Count > 0) { try { foreach (Change change in changes) { if (change is ChangeItem) { var listItemId = (change as ChangeItem).ItemId; log.LogInformation($"-Item that changed: ItemId: {listItemId}"); if (handledListItems.Contains(listItemId)) { log.LogInformation("-ListItem already handled in this batch."); } else { //DO SOMETHING WITH LIST ITEM DoWork(log, cc, changeList, change); } RecordChangeInWebhookHistory(cc, changeList, change, log, notification.Resource); handledListItems.Add(listItemId); } lastChangeToken = change.ChangeToken; } if (changes.Count < changeQuery.FetchLimit) { allChangesRead = true; } } catch (Exception ex) { throw new Exception($"ERROR: {ex.Message}"); } } else { allChangesRead = true; } // Are we done? } while (allChangesRead == false); #endregion #region "Update" the web hook expiration date when needed // Optionally add logic to "update" the expirationdatetime of the web hook // If the web hook is about to expire within the coming 5 days then prolong it try { if (notification.ExpirationDateTime.AddDays(-5) < DateTime.Now) { DateTime newDate = DateTime.Now.AddMonths(3); log.LogInformation($"Updating the Webhook expiration date to {newDate}"); WebHookManager webHookManager = new WebHookManager(); Task <bool> updateResult = Task.WhenAny( webHookManager.UpdateListWebHookAsync( url, changeList.Id.ToString(), notification.SubscriptionId, CloudConfigurationManager.GetSetting("AzureWebJobsStorage"), newDate, cc.GetAccessToken()) ).Result; if (updateResult.Result == false) { throw new Exception(string.Format("The expiration date of web hook {0} with endpoint {1} could not be updated", notification.SubscriptionId, CloudConfigurationManager.GetSetting("WebHookEndPoint"))); } } } catch (Exception ex) { log.LogInformation($"ERROR: {ex.Message}"); //throw new Exception($"ERROR: {ex.Message}"); } #endregion cc.Dispose(); log.LogInformation("Processing complete."); }
public void FraudUpdate(NotificationModel notification) { var order = GetPurchaseOrderByKlarnaOrderId(notification.OrderId); if (order == null) { return; } var orderForm = order.GetFirstForm(); var payment = orderForm.Payments.FirstOrDefault(); if (payment == null) { return; } // Get payment method used and the configuration data var paymentMethodDto = PaymentManager.GetPaymentMethod(payment.PaymentMethodId); var connectionConfiguration = paymentMethodDto.GetConnectionConfiguration(order.MarketId); string userAgent = $"Platform/Episerver.Commerce_{typeof(EPiServer.Commerce.ApplicationContext).Assembly.GetName().Version} Module/Klarna.Common_{typeof(KlarnaService).Assembly.GetName().Version}"; var client = new OrderManagementStore(new ApiSession { ApiUrl = connectionConfiguration.ApiUrl, UserAgent = userAgent, Credentials = new ApiCredentials { Username = connectionConfiguration.Username, Password = connectionConfiguration.Password } }, new JsonSerializer()); // Make sure the order exists in Klarna var klarnaOrder = AsyncHelper.RunSync(() => client.GetOrder(notification.OrderId)); if (klarnaOrder == null) { return; } // Compare fraud status of notification with Klarna order fraud status and stop process if it's still pending or doesn't match switch (klarnaOrder.FraudStatus) { case OrderManagementFraudStatus.ACCEPTED: if (notification.Status != NotificationFraudStatus.FRAUD_RISK_ACCEPTED) { return; } break; case OrderManagementFraudStatus.REJECTED: if (notification.Status != NotificationFraudStatus.FRAUD_RISK_REJECTED) { return; } break; case OrderManagementFraudStatus.PENDING: return; } payment.Status = PaymentStatus.Pending.ToString(); payment.Properties[Constants.FraudStatusPaymentField] = notification.Status; try { var result = order.ProcessPayments(_paymentProcessor, _orderGroupCalculator); if (result.FirstOrDefault()?.IsSuccessful == false) { PaymentStatusManager.FailPayment((Payment)payment); _orderRepository.Save(order); } } catch (Exception ex) { _logger.Error(ex.Message, ex); } _orderRepository.Save(order); }
public async Task <IHttpActionResult> CreateNotification(NotificationModel notification) { var createdNotification = await _notificationService.CreateNotification(notification); return(Ok(createdNotification)); }
private void AddNotification(NotificationModel notification) { Dispatcher.Invoke((Action) (() => cm.Notifications.Add(notification))); }
public NotificationViewModel() { Model = new NotificationModel(); }
private async void Read(NotificationModel model) { // If its already read, ignore it if (!model.Unread) return; try { var response = await this.GetApplication().Client.ExecuteAsync(this.GetApplication().Client.Notifications[model.Id].MarkAsRead()); if (response.Data) { //We just read it model.Unread = false; //Update the notifications count on the account Notifications.Items.Remove(model); UpdateAccountNotificationsCount(); } } catch (Exception e) { ReportError(e); } }
/// <summary> /// 执行定时任务 /// </summary> /// <param name="task">定时任务</param> /// <param name="executeDate">执行时间</param> public void Execute(ScheduledTaskModel task, DateTime executeDate) { if (task == null) { Log.Error("无效的定时任务。"); throw new InvalidOperationException("无效的定时任务。"); } using (var dbContext = new MissionskyOAEntities()) { #region 推送消息 var sql = @"SELECT * FROM BookBorrow WHERE ISNULL([Status], 0) = {0} --借阅中 AND DATEDIFF(DAY, ReturnDate, GETDATE()) >= 0 --已到预计归还日期 ;" ; //推送消息 var notification = new NotificationModel() { CreatedUserId = 0, MessageType = NotificationType.PushMessage, BusinessType = BusinessType.Approving, Title = "Missionsky OA Notification", MessagePrams = "test", Scope = NotificationScope.User, CreatedTime = DateTime.Now }; var entities = dbContext.BookBorrows.SqlQuery(string.Format(sql, (int)UserBorrowStatus.Borrowing)).ToList(); //当前需要归还的借阅图书 entities.ForEach(borrow => { var user = dbContext.Users.FirstOrDefault(it => it.Id == borrow.UserId); var book = dbContext.Books.FirstOrDefault(it => it.Id == borrow.BookId); if (user != null && book != null) { notification.Target = user.Email; notification.TargetUserIds = new List <int> { user.Id }; notification.MessageContent = string.Format("请及时归还您借阅的图书《{0}》。", book.Name); NotificationService.Add(notification, Global.IsProduction); //消息推送 } }); #endregion //更新定时任务 var history = new ScheduledTaskHistoryModel() { TaskId = task.Id, Result = true, Desc = task.Name, CreatedTime = executeDate }; ScheduledTaskService.UpdateTask(dbContext, history); dbContext.SaveChanges(); Log.Info(string.Format("定时任务执行成功: {0}。", task.Name)); } }
/// <summary> /// Processes a received notification. This typically is triggered via an Azure Web Job that reads the Azure storage queue /// </summary> /// <param name="notification">Notification to process</param> public async Task ProcessNotification(NotificationModel notification, TraceWriter log) { ClientContext cc = null; ClientContext acc = null; string notificationStep = "1"; try { #region Setup an app-only client context AuthenticationManager am = new AuthenticationManager(); notificationStep = "1a"; string url = String.Format("https://{0}{1}", System.Environment.GetEnvironmentVariable("TenantName"), notification.SiteUrl); notificationStep = "1b" + url; string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(url)); string approvalUrl = System.Environment.GetEnvironmentVariable("ApprovalSiteUrl"); log.Info("ApprovalSiteUrl: " + approvalUrl); notificationStep = "1b" + url; string approvalRealm = TokenHelper.GetRealmFromTargetUrl(new Uri(approvalUrl)); notificationStep = "1c"; string clientId = System.Environment.GetEnvironmentVariable("ClientId"); notificationStep = "1d"; string clientSecret = System.Environment.GetEnvironmentVariable("ClientSecret"); notificationStep = "2"; if (new Uri(url).DnsSafeHost.Contains("spoppe.com")) { log.Info("Government cloud login (I think)"); cc = am.GetAppOnlyAuthenticatedContext(url, realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"); acc = am.GetAppOnlyAuthenticatedContext(approvalUrl, approvalRealm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"); log.Info("Government cloud login (I think) token received"); } else { log.Info("App only login"); notificationStep = "2"; cc = am.GetAppOnlyAuthenticatedContext(url, clientId, clientSecret); acc = am.GetAppOnlyAuthenticatedContext(approvalUrl, clientId, clientSecret); log.Info("App only login token received"); } notificationStep = "3"; cc.ExecutingWebRequest += Cc_ExecutingWebRequest; #endregion notificationStep = "3a"; #region Grab the list for which the web hook was triggered ListCollection lists = cc.Web.Lists; notificationStep = "3b"; Guid listId = new Guid(notification.Resource); notificationStep = "3c"; log.Info("Loaded source list"); IEnumerable <List> results = cc.LoadQuery <List>(lists.Where(lst => lst.Id == listId)); notificationStep = $"3d-{listId.ToString()},{notification.Resource.ToString()}, {notification.SiteUrl}"; cc.ExecuteQueryRetry(); log.Info("Loaded source list loaded"); notificationStep = "3e"; List notificationSourceList = results.FirstOrDefault(); if (notificationSourceList == null) { // list has been deleted inbetween the event being fired and the event being processed return; } notificationStep = "4"; #endregion #region Grab the list used to write the web hook history // Ensure reference to the history list, create when not available List approvalsList = acc.Web.GetListByTitle("Approvals"); if (approvalsList == null) { log.Info("Creating approvals list as not in place"); approvalsList = acc.Web.CreateList(ListTemplateType.GenericList, "Approvals", false); this.AddTextField(approvalsList, "ClientState", "ClientState", cc); this.AddTextField(approvalsList, "SubscriptionId", "SubscriptionId", cc); this.AddTextField(approvalsList, "ExpirationDateTime", "ExpirationDateTime", cc); this.AddTextField(approvalsList, "Resource", "Resource", cc); this.AddTextField(approvalsList, "TenantId", "TenantId", cc); this.AddTextField(approvalsList, "SiteUrl", "SiteUrl", cc); this.AddTextField(approvalsList, "WebId", "WebId", cc); this.AddTextField(approvalsList, "ItemId", "ItemId", cc); this.AddTextField(approvalsList, "ActivityId", "Activity Id", cc); this.AddTextField(approvalsList, "EditorEmail", "EditorEmail", cc); this.AddTextField(approvalsList, "Activity", "Activity", cc); approvalsList.Update(); acc.ExecuteQuery(); } notificationStep = "5"; #endregion #region Grab the list changes and do something with them // grab the changes to the provided list using the GetChanges method // on the list. Only request Item changes as that's what's supported via // the list web hooks ChangeQuery changeQuery = new ChangeQuery(false, true); changeQuery.Item = true; changeQuery.RecursiveAll = true; changeQuery.User = true; changeQuery.FetchLimit = 1000; // Max value is 2000, default = 1000 notificationStep = "6"; ChangeToken lastChangeToken = null; Guid id = new Guid(notification.SubscriptionId); string storageConnectionString = System.Environment.GetEnvironmentVariable("StorageConnectionString"); const string tableName = "crosssiteappchangetokens"; // Connect to storage account / container var storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(storageConnectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(tableName); notificationStep = "7"; await table.CreateIfNotExistsAsync(); TableResult result = await table.ExecuteAsync(TableOperation.Retrieve <TableChangeToken>("List", id.ToString())); TableChangeToken loadedChangeToken = null; if (result.Result != null) { lastChangeToken = new ChangeToken(); loadedChangeToken = (result.Result as TableChangeToken); lastChangeToken.StringValue = loadedChangeToken.StringValue; } notificationStep = "8"; // Start pulling down the changes bool allChangesRead = false; do { // should not occur anymore now that we record the starting change token at // subscription creation time, but it's a safety net if (lastChangeToken == null) { lastChangeToken = new ChangeToken(); // See https://blogs.technet.microsoft.com/stefan_gossner/2009/12/04/content-deployment-the-complete-guide-part-7-change-token-basics/ lastChangeToken.StringValue = string.Format("1;3;{0};{1};-1", notification.Resource, DateTime.Now.AddMinutes(-5).ToUniversalTime().Ticks.ToString()); } // Assign the change token to the query...this determines from what point in // time we'll receive changes changeQuery.ChangeTokenStart = lastChangeToken; // Execute the change query var changes = notificationSourceList.GetChanges(changeQuery); cc.Load(changes); cc.ExecuteQueryRetry(); notificationStep = "9"; if (changes.Count > 0) { foreach (Change change in changes) { lastChangeToken = change.ChangeToken; if (change is ChangeItem) { // do "work" with the found change DoWork(acc, approvalsList, cc, notificationSourceList, change, notification, log); } } // We potentially can have a lot of changes so be prepared to repeat the // change query in batches of 'FetchLimit' untill we've received all changes if (changes.Count < changeQuery.FetchLimit) { allChangesRead = true; } } else { allChangesRead = true; } // Are we done? } while (allChangesRead == false); // Persist the last used changetoken as we'll start from that one // when the next event hits our service if (loadedChangeToken != null) { // Only persist when there's a change in the change token if (!loadedChangeToken.StringValue.Equals(lastChangeToken.StringValue, StringComparison.InvariantCultureIgnoreCase)) { loadedChangeToken.StringValue = lastChangeToken.StringValue; await table.ExecuteAsync(TableOperation.InsertOrReplace(loadedChangeToken)); notificationStep = "10"; } } else { // should not occur anymore now that we record the starting change token at // subscription creation time, but it's a safety net var newToken = new TableChangeToken() { PartitionKey = "List", RowKey = id.ToString(), StringValue = lastChangeToken.StringValue }; await table.ExecuteAsync(TableOperation.InsertOrReplace(newToken)); notificationStep = "11"; } #endregion #region "Update" the web hook expiration date when needed // Optionally add logic to "update" the expirationdatetime of the web hook // If the web hook is about to expire within the coming 5 days then prolong it if (notification.ExpirationDateTime.AddDays(-5) < DateTime.Now) { WebHookManager webHookManager = new WebHookManager(); Task <bool> updateResult = Task.WhenAny( webHookManager.UpdateListWebHookAsync( url, listId.ToString(), notification.SubscriptionId, System.Environment.GetEnvironmentVariable("WebHookEndPoint"), DateTime.Now.AddMonths(3), this.accessToken) ).Result; notificationStep = "12"; if (updateResult.Result == false) { throw new Exception(String.Format("The expiration date of web hook {0} with endpoint {1} could not be updated", notification.SubscriptionId, System.Environment.GetEnvironmentVariable("WebHookEndPoint"))); } } #endregion } catch (Exception ex) { // Log error //Console.WriteLine(ex.ToString()); throw new Exception("Step " + notificationStep, ex); } finally { if (cc != null) { cc.Dispose(); } } }
private void CreateProtocols(FileSystemPath protocolInstancePath) { if (!protocolInstancePath.ExistsFile) { return; } List <ProtocolInstance> protocolInstanceList; try { protocolInstanceList = ProtocolInstance.FromJson(protocolInstancePath.ReadAllText2().Text); } catch (Exception e) { myLogger.Warn($"Unable to parse {protocolInstancePath}" + Environment.NewLine + e); return; } var protocolInstance = protocolInstanceList?.SingleOrDefault(a => a.SolutionName == mySolution.SolutionFilePath.NameWithoutExtension); if (protocolInstance == null) { return; } myLogger.Info($"EditorPlugin protocol port {protocolInstance.Port} for Solution: {protocolInstance.SolutionName}."); try { var lifetime = mySessionLifetimes.Next(); myLogger.Info("Create protocol..."); myLogger.Info("Creating SocketWire with port = {0}", protocolInstance.Port); var wire = new SocketWire.Client(lifetime, myDispatcher, protocolInstance.Port, "UnityClient"); wire.Connected.WhenTrue(lifetime, lf => { myLogger.Info("WireConnected."); var protocol = new Protocol("UnityEditorPlugin", new Serializers(), new Identities(IdKind.Client), myDispatcher, wire, lf); protocol.ThrowErrorOnOutOfSyncModels = false; protocol.OutOfSyncModels.AdviseOnce(lf, e => { if (myPluginInstallations.Contains(mySolution.SolutionFilePath)) { return; } myPluginInstallations.Add(mySolution.SolutionFilePath); // avoid displaying Notification multiple times on each AppDomain.Reload in Unity var appVersion = myUnityVersion.GetActualVersionForSolution(); if (appVersion < new Version(2019, 2)) { var entry = myBoundSettingsStore.Schema.GetScalarEntry((UnitySettings s) => s.InstallUnity3DRiderPlugin); var isEnabled = myBoundSettingsStore.GetValueProperty <bool>(lf, entry, null).Value; if (!isEnabled) { myHost.PerformModelAction(model => model.OnEditorModelOutOfSync()); } } else { var notification = new NotificationModel("Advanced Unity integration is unavailable", $"Please update External Editor to {myHostProductInfo.VersionMarketingString} in Unity Preferences.", true, RdNotificationEntryType.WARN); mySolution.Locks.ExecuteOrQueue(lifetime, "OutOfSyncModels.Notify", () => myNotificationsModel.Notification(notification)); } }); var editor = new EditorPluginModel(lf, protocol); editor.IsBackendConnected.Set(rdVoid => true); if (PlatformUtil.RuntimePlatform == PlatformUtil.Platform.Windows) { var frontendProcess = Process.GetCurrentProcess().GetParent(); // RiderProcessId is not used on non-Windows, but this line gives bad warning in the log if (frontendProcess != null) { editor.RiderProcessId.SetValue(frontendProcess.Id); } } myHost.PerformModelAction(m => m.SessionInitialized.Value = true); SubscribeToLogs(lf, editor); SubscribeToOpenFile(editor); editor.Play.Advise(lf, b => myHost.PerformModelAction(rd => rd.Play.SetValue(b))); editor.Pause.Advise(lf, b => myHost.PerformModelAction(rd => rd.Pause.SetValue(b))); editor.ClearOnPlay.Advise(lf, time => myHost.PerformModelAction(rd => rd.ClearOnPlay(time))); editor.UnityProcessId.View(lf, (_, pid) => myHost.PerformModelAction(t => t.UnityProcessId.Set(pid))); // I have split this into groups, because want to use async api for finding reference and pass them via groups to Unity myHost.PerformModelAction(t => t.ShowFileInUnity.Advise(lf, v => editor.ShowFileInUnity.Fire(v))); myHost.PerformModelAction(t => t.ShowPreferences.Advise(lf, v => { editor.ShowPreferences.Fire(); })); editor.EditorLogPath.Advise(lifetime, s => myHost.PerformModelAction(a => a.EditorLogPath.SetValue(s))); editor.PlayerLogPath.Advise(lifetime, s => myHost.PerformModelAction(a => a.PlayerLogPath.SetValue(s))); // Note that these are late-init properties. Once set, they are always set and do not allow nulls. // This means that if/when the Unity <-> Backend protocol closes, they still retain the last value // they had - so the front end will retain the log and application paths of the just-closed editor. // Opening a new editor instance will reconnect and push a new value through to the front end editor.ApplicationPath.Advise(lifetime, s => myHost.PerformModelAction(a => a.ApplicationPath.SetValue(s))); editor.ApplicationContentsPath.Advise(lifetime, s => myHost.PerformModelAction(a => a.ApplicationContentsPath.SetValue(s))); editor.ApplicationVersion.Advise(lifetime, s => myHost.PerformModelAction(a => a.ApplicationVersion.SetValue(s))); editor.ScriptCompilationDuringPlay.Advise(lifetime, s => myHost.PerformModelAction(a => a.ScriptCompilationDuringPlay.Set(ConvertToScriptCompilationEnum(s)))); myHost.PerformModelAction(rd => { rd.GenerateUIElementsSchema.Set((l, u) => editor.GenerateUIElementsSchema.Start(l, u).ToRdTask(l)); }); TrackActivity(editor, lf); if (!myComponentLifetime.IsTerminated) { myLocks.ExecuteOrQueueEx(myComponentLifetime, "setModel", () => { UnityModel.SetValue(editor); }); } lf.AddAction(() => { if (!myComponentLifetime.IsTerminated) { myLocks.ExecuteOrQueueEx(myComponentLifetime, "clearModel", () => { myLogger.Info("Wire disconnected."); myHost.PerformModelAction(m => m.SessionInitialized.Value = false); UnityModel.SetValue(null); }); } }); }); } catch (Exception ex) { myLogger.Error(ex); } }
/// <summary> /// notification when contributor or viewer sends a groupshift notification /// </summary> /// <param name="notification">the notification</param> public void SendNotification(NotificationModel notification) { Clients.All.sendNotification(notification); }
private void RefreshAndRunTask(IUnitTestRun run, TaskCompletionSource <bool> tcs, Lifetime taskLifetime) { var cancellationTs = run.GetData(ourCancellationTokenSourceKey); var cancellationToken = cancellationTs.NotNull().Token; myLogger.Trace("Before calling Refresh."); Refresh(run.Lifetime, cancellationToken).ContinueWith(__ => { myLogger.Trace("Refresh. OnCompleted."); // KS: Can't use run.Lifetime for ExecuteOrQueueEx here and in all similar places: run.Lifetime is terminated when // Unit Test Session is closed from UI without cancelling the run. This will leave task completion source in running state forever. mySolution.Locks.ExecuteOrQueueEx(myLifetime, "Check compilation", () => { if (!run.Lifetime.IsAlive || cancellationTs.IsCancellationRequested) { tcs.SetCanceled(); return; } if (myEditorProtocol.UnityModel.Value == null) { myLogger.Verbose("Unity Editor connection unavailable."); tcs.SetException(new Exception("Unity Editor connection unavailable.")); return; } var task = myEditorProtocol.UnityModel.Value.GetCompilationResult.Start(Unit.Instance); task.Result.AdviseNotNull(myLifetime, result => { if (!run.Lifetime.IsAlive || cancellationTs.IsCancellationRequested) { tcs.SetCanceled(); } else if (!result.Result) { tcs.SetException(new Exception("There are errors during compilation in Unity.")); mySolution.Locks.ExecuteOrQueueEx(run.Lifetime, "RunViaUnityEditorStrategy compilation failed", () => { var notification = new NotificationModel("Compilation failed", "Script compilation in Unity failed, so tests were not started.", true, RdNotificationEntryType.INFO); myNotificationsModel.Notification(notification); }); myUnityHost.PerformModelAction(model => model.ActivateUnityLogView()); } else { var launch = SetupLaunch(run); mySolution.Locks.ExecuteOrQueueEx(myLifetime, "ExecuteRunUT", () => { if (!run.Lifetime.IsAlive || cancellationTs.IsCancellationRequested) { tcs.SetCanceled(); return; } if (myEditorProtocol.UnityModel.Value == null) { tcs.SetException(new Exception("Unity Editor connection unavailable.")); return; } myEditorProtocol.UnityModel.ViewNotNull(taskLifetime, (lt, model) => { // recreate UnitTestLaunch in case of AppDomain.Reload, which is the case with PlayMode tests model.UnitTestLaunch.SetValue(launch); SubscribeResults(run, lt, tcs, launch); }); myUnityProcessId.When(taskLifetime, (int?)null, _ => tcs.TrySetException(new Exception("Unity Editor has been closed."))); var rdTask = myEditorProtocol.UnityModel.Value.RunUnitTestLaunch.Start(Unit.Instance); rdTask?.Result.Advise(taskLifetime, res => { myLogger.Trace($"RunUnitTestLaunch result = {res.Result}"); if (!res.Result) { var defaultMessage = "Failed to start tests in Unity."; var isCoverage = run.HostController.HostId != WellKnownHostProvidersIds.DebugProviderId && run.HostController.HostId != WellKnownHostProvidersIds.RunProviderId; if (myPackageValidator.HasNonCompatiblePackagesCombination(isCoverage, out var message)) { defaultMessage = $"{defaultMessage} {message}"; } if (myEditorProtocol.UnityModel.Value.UnitTestLaunch.Value.TestMode == TestMode.Play) { if (!myPackageValidator.CanRunPlayModeTests(out var playMessage)) { defaultMessage = $"{defaultMessage} {playMessage}"; } } tcs.TrySetException(new Exception(defaultMessage)); } }); }); } });
public NotificationsViewModel() { NotificationItems = new NotificationModel(); }
public async Task <IHttpActionResult> SendNotification(NotificationModel model) { var receivers = new List <int>(); if (model.ReceiverType == ReceiverType.UserIds || model.ReceiverType == ReceiverType.Both) { switch (model.NotificationType) { case NotificationType.Verify_Courses_Creation: receivers = await GetUserIds(UserAccess.CourseVerify); break; case NotificationType.Approve_Courses_Creation_Approver1: receivers = await GetUserIds(UserAccess.CourseApproval1); break; case NotificationType.Approve_Courses_Creation_Approver2: receivers = await GetUserIds(UserAccess.CourseApproval2); break; case NotificationType.Approve_Courses_Creation_Approver3: receivers = await GetUserIds(UserAccess.CourseApproval3); break; case NotificationType.Course_Amendment: receivers = await GetUserIds(UserAccess.CourseCreate); break; case NotificationType.Course_Approved: receivers = await GetUserIds(UserAccess.CourseCreate); break; case NotificationType.Course_Assigned_To_Facilitator: //get trainer assigned to the course receivers = model.Receivers; break; case NotificationType.Course_Student_Enrolled: receivers = await GetCourseTrainers(model.Id); // get student name var user = await db.User.FindAsync(model.SenderId); model.ParameterListToSend.LearnerName = user != null ? user.Name : ""; break; case NotificationType.Notify_Admin_Participant_Withdraw: var admin = await db.Courses.FindAsync(model.Id); if (admin != null) { receivers.Add(admin.CreatedBy); } break; case NotificationType.Notify_Self_Withdraw_From_Course: case NotificationType.Verify_Courses_Creation_Self: case NotificationType.Approve_Courses_Creation_Approver_Self: case NotificationType.Course_Amendment_Self: receivers.Add(model.SenderId); break; case NotificationType.Course_Approved_Others: receivers.AddRange(await GetUserIds(UserAccess.CourseVerify)); break; case NotificationType.Course_Approved_Self: receivers.Add(model.SenderId); break; case NotificationType.Course_Publish: receivers.Add(model.SenderId); receivers.AddRange(await GetUserIds(UserAccess.CourseVerify)); receivers.AddRange(await GetUserIds(UserAccess.CourseApproval1)); receivers.AddRange(await GetUserIds(UserAccess.CourseApproval2)); receivers.AddRange(await GetUserIds(UserAccess.CourseApproval3)); break; case NotificationType.Course_Cancelled: receivers.Add(model.SenderId); var approval = db.CourseApprovals.Where(x => x.CourseId == model.Id).OrderByDescending(x => x.CreatedDate).FirstOrDefault(); if (approval != null) { if (approval.ApprovalLevel == ApprovalLevel.Verifier) { receivers.AddRange(await GetUserIds(UserAccess.CourseVerify)); } if (approval.ApprovalLevel == ApprovalLevel.Approver1) { receivers.AddRange(await GetUserIds(UserAccess.CourseApproval1)); } if (approval.ApprovalLevel == ApprovalLevel.Approver2) { receivers.AddRange(await GetUserIds(UserAccess.CourseApproval2)); } if (approval.ApprovalLevel == ApprovalLevel.Approver3) { receivers.AddRange(await GetUserIds(UserAccess.CourseApproval3)); } } break; default: break; } if (model.ReceiverId == null) { model.ReceiverId = new List <int>(); } model.ReceiverId.AddRange(receivers); } if (model.Type == typeof(Course)) { var course = await db.Courses.FindAsync(model.Id); if (course != null) { model.ParameterListToSend.CourseTitle = course.Title; } } await db.SaveChangesAsync(); var controller = new SLAReminderController(); try { if (model.IsNeedRemainder) { CreateAutoReminder createdAutoReminder = new CreateAutoReminder { NotificationCategory = model.NotificationCategory, NotificationType = model.NotificationType, ParameterListToSend = model.ParameterListToSend, ReceiverId = model.ReceiverId, StartNotificationDate = DateTime.Now }; var result = await controller.GenerateAutoNotificationReminder(createdAutoReminder); var response = result as OkNegotiatedContentResult <ReminderResponse>; if (response != null) { if (model.Type == typeof(Course)) { var course = await db.Courses.FindAsync(model.Id); if (course != null) { course.SLAReminderId = response.Content.SLAReminderStatusId; db.SetModified(course); await db.SaveChangesAsync(); return(Ok()); } } } else { var log = new ErrorLog { CreatedDate = DateTime.Now, UserId = null, Module = null, Source = " Controller: eLearning/NotificationApi Action: SendNotification", ErrorDescription = "Error sending email", ErrorDetails = "Null response", IPAddress = "", }; db.ErrorLog.Add(log); db.SaveChanges(); } } else { var result = await controller.GenerateAndSendEmails(model); var response = result as OkNegotiatedContentResult <ReminderResponse>; if (response == null) { var log = new ErrorLog { CreatedDate = DateTime.Now, UserId = null, Module = null, Source = " Controller: eLearning/NotificationApi Action: SendNotification", ErrorDescription = "Error sending email", ErrorDetails = "Null response", IPAddress = "", }; db.ErrorLog.Add(log); db.SaveChanges(); } } } catch (Exception e) { var log = new ErrorLog { CreatedDate = DateTime.Now, UserId = null, Module = null, Source = " Controller: eLearning/NotificationApi Action: SendNotification", ErrorDescription = e.Message, ErrorDetails = e.InnerException + " | " + e.StackTrace, IPAddress = "", }; db.ErrorLog.Add(log); db.SaveChanges(); } return(Ok()); }
//Create new Adjustment public static AdjustmentModel CreateAdjustment(AdjustmentModel adjm, out string error) { error = ""; LUSSISEntities entities = new LUSSISEntities(); adjustment adj = new adjustment(); try { adj.raisedby = adjm.Raisedby; adj.issueddate = adjm.Issueddate; adj.status = ConAdjustment.Active.PENDING; List <AdjustmentDetailModel> adjds = adjm.Adjds; //check item price foreach (AdjustmentDetailModel adjd in adjds) { adj.raisedto = 0; SupplierItemModel supp = SupplierItemRepo.GetSupplierItemByItemId(adjd.Itemid, out error); double? price = Math.Abs((Int32)adjd.Adjustedqty) * supp.Price; //Check total price of each item to consider who to report to if (price >= ConAdjustment.Active.REPORTMANAGER) { user user = entities.users.Where(u => u.role == ConUser.Role.MANAGER).First(); adj.raisedto = user.userid; } else { user user = entities.users.Where(u => u.role == ConUser.Role.SUPERVISOR).First(); adj.raisedto = user.userid; } } adj = entities.adjustments.Add(adj); entities.SaveChanges(); foreach (AdjustmentDetailModel adjdm in adjds) { adjustmentdetail adjd = new adjustmentdetail { adjid = adj.adjid, itemid = adjdm.Itemid, adjustedqty = adjdm.Adjustedqty, reason = adjdm.Reason }; adjd = entities.adjustmentdetails.Add(adjd); entities.SaveChanges(); } adjm = GetAdjustmentByID(adj.adjid, out error); NotificationModel nom = new NotificationModel(); nom.Deptid = DepartmentRepo.GetDepartmentByUserid(adj.raisedto ?? default(int), out error).Deptid; nom.Role = UserRepo.GetUserByUserID(adj.raisedto ?? default(int)).Role; nom.Title = "New Adjustment"; nom.NotiType = ConNotification.NotiType.Adjustment; nom.ResID = adj.adjid; nom.Remark = "A new adjustment has been raised by clerk!"; nom = NotificationRepo.CreatNotification(nom, out error); } catch (NullReferenceException) { error = ConError.Status.NOTFOUND; } catch (Exception e) { error = e.Message; } return(adjm); }
public async Task PublishNotification(NotificationModel model) { await Clients.All.InvokeAsync("OnSendingNotification", model); }
private static Action<object> MakeCallback(WeakReference<NotificationsViewModel> weakVm, NotificationModel model) { return new Action<object>(_ => weakVm.Get()?.GoToNotificationCommand.Execute(model)); }
public void ShowNotification(NotificationModel model) { }
private bool UpdateIsOurCharacter(NotificationModel param) { var updateModel = param as CharacterUpdateModel; if (updateModel == null) return false; var args = updateModel.TargetCharacter; return args.Name.Equals(ConversationWith.Name, StringComparison.OrdinalIgnoreCase); }
public async Task <IActionResult> Post([FromBody] UserModel userModel) { UserModel um = await _userService.Get(userModel.email); VerificationDetailModel vDetails = new VerificationDetailModel() { CreatedBy = User.Identity.Name, VerificationCode = _codeGenerationService.VerificationCode() }; if (um != null) { vDetails.OwnerId = um.id.ToString(); ResponseModel responseModel = new ResponseModel(); responseModel.code = ResponseCode.FAIL; if (um.userStatus == UserStatus.PENDING) { bool vResult = await _verificationService.Add(vDetails); if (vResult) { string template = await _templateService.GetTemplate(TemplateType.EMAIL_CONFIRMATION); if (!string.IsNullOrEmpty(template)) { template = template.Replace("$FULLNAME$", $"{userModel.lastname} {userModel.otherNames}"); template = template.Replace("$VERIFICATION_URL$", $"{_configuration["domainUrl"]}/api/v2.0/user/verify/{um.id}/{vDetails.VerificationCode}"); NotificationModel notificationModel = new NotificationModel() { Content = template, ContentType = EmailContentType.HTML, Title = "Email Verification", ToEmails = new List <string>() { um.email }, FromEmail = _configuration["EmailConfiguration:VerificationEmail"] }; await _emailService.Send(notificationModel); } } responseModel.description = $"An email has been send to your email for verification"; } return(Ok(responseModel)); } bool result = await _userService.Add(userModel); if (result) { UserModel umm = await _userService.Get(userModel.email); vDetails.OwnerId = umm.id.ToString(); bool vResult = await _verificationService.Add(vDetails); if (vResult) { string template = await _templateService.GetTemplate(TemplateType.EMAIL_CONFIRMATION); if (!string.IsNullOrEmpty(template)) { template = template.Replace("$FULLNAME$", $"{userModel.lastname} {userModel.otherNames}"); template = template.Replace("$VERIFICATION_URL$", $"{_configuration["domainUrl"]}/api/v2.0/user/verify/{umm.id}/{vDetails.VerificationCode}"); NotificationModel notificationModel = new NotificationModel() { Content = template, ContentType = EmailContentType.HTML, Title = "Email Verification", ToEmails = new List <string>() { umm.email }, FromEmail = _configuration["EmailConfiguration:VerificationEmail"] }; await _emailService.Send(notificationModel); } } return(Ok(new ResponseModel() { code = ResponseCode.SUCCESSFULL, description = $"{userModel.email} has been created successfully", data = umm.id })); } throw new UnknownException("An error occurred while trying to create a your login details. Please try again or contact your administrator"); }
public void LogMessage(string title, NotificationModel model) { using (var writer = AccessLog(title, title)) { var thisMessage = HttpUtility.HtmlDecode(model.ToString()); var timestamp = model.TimeStamp; writer.WriteLine(timestamp + ' ' + thisMessage); } }
public async Task <ApiResponseResult> SaveNotification(NotificationModel notificationModel) { return(await notificationService.SaveNotification(notificationModel)); }
private async Task Read(NotificationModel model) { // If its already read, ignore it if (!model.Unread) return; try { var response = await this.GetApplication().Client.ExecuteAsync(this.GetApplication().Client.Notifications[model.Id].MarkAsRead()); if (response.Data) { //We just read it model.Unread = false; //Update the notifications count on the account Notifications.Items.Remove(model); UpdateAccountNotificationsCount(); } } catch (Exception e) { DisplayAlert("Unable to mark notification as read. Please try again."); } }
public IosPush() { aps = new aps(); notification = new NotificationModel(); }
public void TestInitialize() { testModel = new TestModel { Bool = false, Byte = byte.MinValue, Char = char.MinValue, DateTime = DateTime.MinValue, Decimal = decimal.MinValue, Double = double.MinValue, Float = float.MinValue, Int = int.MinValue, Long = long.MinValue, Short = short.MinValue, String = string.Empty }; notificationModel = new NotificationModel<TestModel>(testModel); dynamicModel = notificationModel; }
//public async Task SendIosPushNotification(List<UserDevice> devices, string Text) //{ // string serverKey = GCMApiKey; // var result = "-1"; // var notificationid = 0; // try // { // var webAddr = "https://fcm.googleapis.com/fcm/send"; // foreach (var device in devices) // { // var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); // httpWebRequest.ContentType = "application/json"; // httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "key=" + serverKey); // //httpWebRequest.Headers.Add("Authorization:key=" + serverKey); // httpWebRequest.Method = "POST"; // using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) // { // string json = ""; // json = "{\"to\": \"" + device.AuthToken + "\",\"data\": {\"message\": \"" + Text + "\",\"title\": \"" + Text + "\",\"notificationid\": \"" + notificationid + "\",\"isread\": \"" + true + "\",}}"; // streamWriter.Write(json); // streamWriter.Flush(); // } // var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) // { // result = streamReader.ReadToEnd(); // if (result.Contains("success") && result.Contains("failure")) // { // dynamic token = JObject.Parse(result); // string success = token.success.ToString(); // //return success == "1" ? true : false; // } // else // { // } // } // } // // return result; // } // catch (Exception ex) // { // } //} //public void SendIOSPushNotification(List<UserDevice> devices, AdminNotifications AdminNotification = null, Notification OtherNotification = null, int Type = 0) public static async Task SendIOSPushNotification(List <string> devices, bool isIOS, NotificationModel OtherNotification = null, int Type = 0) { string serverKey = ServerKeyDriver; var result = "-1"; var notificationid = 0; try { var webAddr = "https://fcm.googleapis.com/fcm/send"; foreach (var device in devices) { var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json"; httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "key=" + serverKey); httpWebRequest.Headers.Add(string.Format("Sender: id={0}", SenderId)); //httpWebRequest.Headers.Add("Authorization:key=" + serverKey); httpWebRequest.Method = "POST"; IosPush pushModel = new IosPush(); pushModel.aps.alert.title = OtherNotification.Title; pushModel.aps.alert.body = OtherNotification.Text; pushModel.notification.Type = Type; pushModel.aps.contentavailable = 1; using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = ""; if (isIOS) { json = "{\"to\": \"" + devices + "\",\"notification\": {\"body\": \"" + pushModel.aps.alert.body + "\",\"title\": \"" + pushModel.aps.alert.title + "\",\"notificationid\": \"" + pushModel.notification.NotificationId + "\",\"orderid\": \"" + pushModel.notification.EntityId + "\",\"isread\": \"" + true + "\",}}"; } else { json = "{\"to\": \"" + devices + "\",\"data\": {\"body\": \"" + pushModel.aps.alert.body + "\",\"title\": \"" + pushModel.aps.alert.title + "\",\"notificationid\": \"" + pushModel.notification.NotificationId + "\",\"orderid\": \"" + pushModel.notification.EntityId + "\",\"isread\": \"" + true + "\",}}"; } //json = "{\"to\": \"" + device.AuthToken + "\",\"notification\": {\"body\": \"" + Text + "\",\"title\": \"" + Text + "\",}}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); if (result.Contains("success") && result.Contains("failure")) { dynamic token = JObject.Parse(result); string success = token.success.ToString(); //return success == "1" ? true : false; } else { } } } // return result; } catch (Exception ex) { } }
private void ConvertNotificationLevelToAction( int notificationLevel, string actionId, NotificationModel notification) { switch ((ChannelSettingsModel.NotifyLevel) notificationLevel) { // convert our int into an enum to avoid magic numbers case ChannelSettingsModel.NotifyLevel.NoNotification: return; case ChannelSettingsModel.NotifyLevel.NotificationOnly: AddNotification(notification); return; case ChannelSettingsModel.NotifyLevel.NotificationAndToast: AddNotification(notification); NotifyUser(false, false, notification.ToString(), actionId); return; case ChannelSettingsModel.NotifyLevel.NotificationAndSound: AddNotification(notification); NotifyUser(true, true, notification.ToString(), actionId); return; } }
private void Install(UnityPluginDetector.InstallationInfo installationInfo, bool force) { if (!force) { if (!installationInfo.ShouldInstallPlugin) { Assertion.Assert(false, "Should not be here if installation is not required."); return; } if (myPluginInstallations.Contains(mySolution.SolutionFilePath)) { myLogger.Verbose("Installation already done."); return; } } myLogger.Info("Installing Rider Unity editor plugin: {0}", installationInfo.InstallReason); if (!TryCopyFiles(installationInfo, out var installedPath)) { myLogger.Warn("Plugin was not installed"); } else { string userTitle; string userMessage; switch (installationInfo.InstallReason) { case UnityPluginDetector.InstallReason.FreshInstall: userTitle = "Unity Editor plugin installed"; userMessage = $@"Please switch to Unity Editor to load the plugin. Rider plugin v{myCurrentVersion} can be found at: {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}."; break; case UnityPluginDetector.InstallReason.Update: userTitle = "Unity Editor plugin updated"; userMessage = $@"Please switch to the Unity Editor to reload the plugin. Rider plugin v{myCurrentVersion} can be found at: {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}."; break; case UnityPluginDetector.InstallReason.ForceUpdateForDebug: userTitle = "Unity Editor plugin updated (debug build)"; userMessage = $@"Please switch to the Unity Editor to reload the plugin. Rider plugin v{myCurrentVersion} can be found at: {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}."; break; case UnityPluginDetector.InstallReason.UpToDate: userTitle = "Unity Editor plugin updated (up to date)"; userMessage = $@"Please switch to the Unity Editor to reload the plugin. Rider plugin v{myCurrentVersion} can be found at: {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}."; break; default: myLogger.Error("Unexpected install reason: {0}", installationInfo.InstallReason); return; } myLogger.Info(userTitle); var notification = new NotificationModel(userTitle, userMessage, true, RdNotificationEntryType.INFO); myShellLocks.ExecuteOrQueueEx(myLifetime, "UnityPluginInstaller.Notify", () => myNotifications.Notification(notification)); } }
private void UpdateChat(NotificationModel newUpdate) { var updateModel = newUpdate as CharacterUpdateModel; if (updateModel == null) return; var args = updateModel.Arguments as CharacterUpdateModel.ListChangedEventArgs; if (args == null) return; messageManager.RebuildItems(); }
public ActionResult Comment(int postId, String userId, String content, HttpPostedFileBase image) { var service = this.Service <IPostCommentService>(); var notiService = this.Service <INotificationService>(); var postService = this.Service <IPostService>(); var aspNetUserService = this.Service <IAspNetUserService>(); var likeService = this.Service <ILikeService>(); ResponseModel <PostCommentDetailViewModel> response = null; try { String commentImage = null; if (image != null) { FileUploader uploader = new FileUploader(); commentImage = uploader.UploadImage(image, userImagePath); } PostComment comment = service.Comment(postId, userId, content, commentImage); AspNetUser commentedUser = aspNetUserService.FindUser(comment.UserId); Post post = postService.GetPostById(comment.PostId); post.LatestInteractionTime = DateTime.Now; AspNetUser user = aspNetUserService.FindUser(post.UserId); List <string> AllRelativeUserIdOfPost = new List <string>(); List <PostComment> listPostCmt = service.GetAllRelativeCmtDistinct(postId).ToList(); List <Like> listPostLike = likeService.GetAllRelativeLikeDistinct(postId).ToList(); foreach (var item in listPostCmt) { AllRelativeUserIdOfPost.Add(item.UserId); } foreach (var item in listPostLike) { AllRelativeUserIdOfPost.Add(item.UserId); } AllRelativeUserIdOfPost = AllRelativeUserIdOfPost.Distinct().ToList(); //Noti to post creator if (!(post.UserId.Equals(commentedUser.Id))) { string u = post.UserId; string u1 = commentedUser.Id; Notification notiForPostCreator = notiService.SaveNoti(u, u1, "Comment", commentedUser.FullName + " đã bình luận về bài viết của bạn", int.Parse(NotificationType.Post.ToString("d")), post.Id, null, null); //Fire base noti List <string> registrationIds = GetToken(user.Id); //registrationIds.Add("dgizAK4sGBs:APA91bGtyQTwOiAgNHE_mIYCZhP0pIqLCUvDzuf29otcT214jdtN2e9D6iUPg3cbYvljKbbRJj5z7uaTLEn1WeUam3cnFqzU1E74AAZ7V82JUlvUbS77mM42xHZJ5DifojXEv3JPNEXQ"); NotificationModel model = Mapper.Map <NotificationModel>(PrepareNotificationViewModel(notiForPostCreator)); if (registrationIds != null && registrationIds.Count != 0) { Android.Notify(registrationIds, null, model); } //SignalR Noti NotificationFullInfoViewModel notiModelR = notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(notiForPostCreator)); // Get the context for the Pusher hub IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>(); // Notify clients in the group hubContext.Clients.User(notiModelR.UserId).send(notiModelR); } //noti to all user that relavtive in this post foreach (var item in AllRelativeUserIdOfPost) { if (!(item.Equals(commentedUser.Id)) && !(item.Equals(post.UserId))) { string i = item; string i1 = commentedUser.Id; Notification not = notiService.SaveNoti(item, commentedUser.Id, "Comment", commentedUser.FullName + " đã bình luận về bài viết mà bạn theo dõi", int.Parse(NotificationType.Post.ToString("d")), post.Id, null, null); Notification noti = notiService.FirstOrDefaultActive(n => n.Id == not.Id); //Fire base noti List <string> registrationIds = GetToken(item); //registrationIds.Add("dgizAK4sGBs:APA91bGtyQTwOiAgNHE_mIYCZhP0pIqLCUvDzuf29otcT214jdtN2e9D6iUPg3cbYvljKbbRJj5z7uaTLEn1WeUam3cnFqzU1E74AAZ7V82JUlvUbS77mM42xHZJ5DifojXEv3JPNEXQ"); NotificationModel model = Mapper.Map <NotificationModel>(PrepareNotificationViewModel(noti)); if (registrationIds != null && registrationIds.Count != 0) { Android.Notify(registrationIds, null, model); } //SignalR Noti NotificationFullInfoViewModel notiModelR = notiService.PrepareNoti(Mapper.Map <NotificationFullInfoViewModel>(noti)); // Get the context for the Pusher hub IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext <RealTimeHub>(); // Notify clients in the group hubContext.Clients.User(notiModelR.UserId).send(notiModelR); } } PostCommentDetailViewModel result = PreparePostCommentDetailViewModel(comment); response = new ResponseModel <PostCommentDetailViewModel>(true, "Bình luận thành công", null, result); } catch (Exception) { response = ResponseModel <PostCommentDetailViewModel> .CreateErrorResponse("Bình luận thất bại", systemError); } return(Json(response)); }
public ApiResponse <bool> AddMeetingByWeeks(ReserveMeetingModel model, int loopCount) { // 1. 检查输入参数 if (model == null) { throw new ApiBadRequestException("无请求数据"); } if (model.MeetingRoomId == 0) { throw new ApiBadRequestException("会议室不存在"); } if (loopCount > 10) { throw new ApiBadRequestException("会议循环次数不能大于十次"); } if (model.MeetingDayInWeek == null || model.MeetingDayInWeek.Length < 1) { throw new ApiBadRequestException("请选择会议举办日期"); } if (model.StartDate >= model.EndDate) { throw new ApiBadRequestException("会议开始时间必须小于结束时间"); } bool isMeetingAdded = false; if (model.MeetingDayInWeek != null && model.MeetingDayInWeek.Length > 0) { DateTime today = DateTime.Now; int TodayInDayOfWeek = (int)today.DayOfWeek; DateTime WeekStartDateStartTime = today.AddDays(-TodayInDayOfWeek).Date + model.StartDate.TimeOfDay; //当前星期的星期天会议开始时间 DateTime WeekStartDateEndTime = today.AddDays(-TodayInDayOfWeek).Date + model.EndDate.TimeOfDay; //当前星期的星期天会议结束时间 for (int i = 0; i <= loopCount; i++) { for (int j = 0; j < model.MeetingDayInWeek.Length; j++) { DateTime StartDate = WeekStartDateStartTime.AddDays((int)model.MeetingDayInWeek[j]); DateTime EndDate = WeekStartDateEndTime.AddDays((int)model.MeetingDayInWeek[j]); if (StartDate > today) { if (MeetingService.isMeetingRoomAvailiable(model.MeetingRoomId, StartDate, EndDate) == false) { throw new ApiBadRequestException("会议室已经占用"); } else { // 2. 构造会议预约记录 var meetingCalendar = new MeetingCalendarModel() { ApplyUserId = this.Member.Id, MeetingRoomId = model.MeetingRoomId, Title = model.Title, Host = model.Host, StartDate = StartDate, EndDate = EndDate, MeetingContext = model.MeetingContext, StartTime = model.StartDate.TimeOfDay, EndTime = model.EndDate.TimeOfDay, CreatedTime = DateTime.Now }; //2.1 构造会议必须参与人员模型 List <MeetingParticipantModel> meetingParticipants = new List <MeetingParticipantModel>(); if (model.participants != null && (model.participants.Length > 0)) { foreach (int item in model.participants) { var meetingParticipantModel = new MeetingParticipantModel() { UserId = item, IsOptional = "No" }; meetingParticipants.Add(meetingParticipantModel); } } //2.1 构造会议可选参与人员模型 if (model.optionalParticipants != null && (model.optionalParticipants.Length > 0)) { foreach (int item in model.optionalParticipants) { var meetingParticipantModel = new MeetingParticipantModel() { UserId = item, IsOptional = "Yes" }; meetingParticipants.Add(meetingParticipantModel); } } meetingCalendar.MeetingParticipants = meetingParticipants; MeetingService.AddMeeting(meetingCalendar, true); isMeetingAdded = true; } } } WeekStartDateStartTime = WeekStartDateStartTime.AddDays(7); //下次预定会议的星期天 WeekStartDateEndTime = WeekStartDateEndTime.AddDays(7); //下次的星期天会议结束数据 } } if (isMeetingAdded) { if (model.participants != null && (model.participants.Length > 0)) { foreach (int item in model.participants) { var userEntity = this.UserService.GetUserDetail(item); var notificationModel = new NotificationModel() { Target = userEntity.Email, CreatedUserId = this.Member.Id, //MessageType = NotificationType.PushMessage, MessageType = NotificationType.Email, BusinessType = BusinessType.BookMeetingRoomSuccessAnnounce, Title = "Missionsky OA Notification", MessagePrams = "test", Scope = NotificationScope.User, CreatedTime = DateTime.Now, TargetUserIds = new List <int> { userEntity.Id } }; if (loopCount > 0) { string MeetingHappenedDate = null; for (int i = 0; i < model.MeetingDayInWeek.Length; i++) { MeetingHappenedDate = MeetingHappenedDate + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(model.MeetingDayInWeek[i]) + ","; } notificationModel.MessageContent = string.Format("请参加,于每周{0}{1}召开,由{2}主持的{3}会议,会议持续循环召开{4}周", MeetingHappenedDate, model.StartDate.TimeOfDay, model.Host, model.Title, loopCount + 1); } else { string MeetingHappenedDate = null; for (int i = 0; i < model.MeetingDayInWeek.Length; i++) { if (model.MeetingDayInWeek[i] >= DateTime.Now.DayOfWeek) { MeetingHappenedDate = MeetingHappenedDate + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(model.MeetingDayInWeek[i]) + ","; } } notificationModel.MessageContent = string.Format("请参加,于本周{0}{1}召开,由{2}主持的{3}会议", MeetingHappenedDate, model.StartDate.TimeOfDay, model.Host, model.Title, loopCount + 1); } this._notificationService.Add(notificationModel, Global.IsProduction); //消息推送 } } } //新增会议预约 // 3. Construct API Response ApiResponse <bool> response = new ApiResponse <bool>() { Result = isMeetingAdded }; return(response); }
private static Action <object> MakeCallback(WeakReference <NotificationsViewModel> weakVm, NotificationModel model) { return(new Action <object>(_ => weakVm.Get()?.GoToNotificationCommand.Execute(model))); }
private async Task ReadNotification(NotificationModel notification) { try { if (notification == null) return; if (!notification.Unread) return; var response = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Notifications[notification.Id].MarkAsRead()); if (response.Data) { notification.Unread = false; Notifications.Remove(notification); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Unable to mark notification as read: " + e.Message); } }
public Notification(NotificationModel model) : this(model.Header, model.Text, model.Timeout) { }
private bool MeetsFilter(NotificationModel item) { return item.ToString().ContainsOrdinal(search); }
private async Task <Response> ReportNonRequestIssue(int providerId, string type, IssueState issue, string comment) { var currentIssues = await IssuesService.GetAllAsync(); var notifyModel = new NotificationModel { User = Username, NotificationType = NotificationType.Issue, DateTime = DateTime.Now, Body = issue == IssueState.Other ? comment : issue.ToString().ToCamelCaseWords() }; var model = new IssueModel { Issue = issue, UserReported = Username, UserNote = !string.IsNullOrEmpty(comment) ? $"{Username} - {comment}" : string.Empty, }; var existing = currentIssues.FirstOrDefault(x => x.ProviderId == providerId && !x.Deleted && x.IssueStatus == IssueStatus.PendingIssue); if (existing != null) { existing.Issues.Add(model); await IssuesService.UpdateIssueAsync(existing); return(Response.AsJson(new JsonResponseModel { Result = true })); } if (type == "movie") { var movieApi = new TheMovieDbApi(); var result = await movieApi.GetMovieInformation(providerId); if (result != null) { notifyModel.Title = result.Title; // New issue var issues = new IssuesModel { Title = result.Title, PosterUrl = "https://image.tmdb.org/t/p/w150/" + result.PosterPath, ProviderId = providerId, Type = RequestType.Movie, IssueStatus = IssueStatus.PendingIssue }; issues.Issues.Add(model); var issueId = await IssuesService.AddIssueAsync(issues); await NotificationService.Publish(notifyModel); return(Response.AsJson(new JsonResponseModel { Result = true })); } } if (type == "tv") { var tv = new TvMazeApi(); var result = tv.ShowLookupByTheTvDbId(providerId); if (result != null) { var banner = result.image?.medium; if (!string.IsNullOrEmpty(banner)) { banner = banner.Replace("http", "https"); } notifyModel.Title = result.name; // New issue var issues = new IssuesModel { Title = result.name, PosterUrl = banner, ProviderId = providerId, Type = RequestType.TvShow, IssueStatus = IssueStatus.PendingIssue }; issues.Issues.Add(model); var issueId = await IssuesService.AddIssueAsync(issues); await NotificationService.Publish(notifyModel); return(Response.AsJson(new JsonResponseModel { Result = true })); } } return(Response.AsJson(new JsonResponseModel { Result = false, Message = "Album Reports are not supported yet!" })); }