public void RevealResourceNotification(ResourceType thisType, int thisAmount, bool isReduce = false, string fromDesc = "") { BaseNotification selectedNotif = notifList.Find(x => !x.isShowing); selectedNotif.gameObject.SetActive(true); selectedNotif.SetIconTo(thisType); if (isReduce) { selectedNotif.SetAsReduce(); } else { selectedNotif.SetAsAdd(); } selectedNotif.SetShowing(true); if (!string.IsNullOrEmpty(fromDesc)) { selectedNotif.text.postCountMesg = fromDesc; } else { selectedNotif.text.postCountMesg = ""; } selectedNotif.text.SetTargetCount(thisAmount); StartCoroutine(selectedNotif.myPanel.WaitAnimationForAction(selectedNotif.myPanel.openAnimationName, selectedNotif.PreCloseAnim)); }
public async Task SendNotification(NotificationScope scope, BaseNotification notification) { ArgumentNullException.ThrowIfNull(scope); ArgumentNullException.ThrowIfNull(notification); var users = await GetUsers(scope, notification.Identifier); await using (var db = _contextFactory.CreateContext()) { foreach (var uid in users) { var obj = JsonConvert.SerializeObject(notification); var data = new NotificationData { Id = Guid.NewGuid().ToString(), Created = DateTimeOffset.UtcNow, ApplicationUserId = uid, NotificationType = notification.NotificationType, Blob = ZipUtils.Zip(obj), Seen = false }; await db.Notifications.AddAsync(data); } await db.SaveChangesAsync(); } foreach (string user in users) { _notificationManager.InvalidateNotificationCache(user); } }
private void GenericSubscriptionQueue_MessageReceived (RabbitMQ.Client.IBasicConsumer sender, RabbitMQ.Client.Events.BasicDeliverEventArgs args) { RabbitMQ.Client.Events.EventingBasicConsumer consumer = (RabbitMQ.Client.Events.EventingBasicConsumer)sender; try { // don't reprocess items that have been processed if (genericSubscriptionQueue.GetLastProcessedUndelivered() != args.DeliveryTag) { BaseNotification notification = NotificationExtension.Deserialize(Encoding.ASCII.GetString(args.Body)); eventLogRepository.WriteInformationLog("Processing notification type: {NotificationType}. Data: {QueueMessage}".Inject(new { QueueMessage = notification.ToJson(), NotificationType = notification.NotificationType.ToString() })); var handler = notificationHandlerFactory(notification.NotificationType); // autofac will get the right handler handler.ProcessNotification(notification); // Always clear the context at the end of a transaction _uow.ClearContext(); } genericSubscriptionQueue.Ack(consumer, args.DeliveryTag); } catch (QueueDataError <string> serializationEx) { eventLogRepository.WriteErrorLog("Serializing problem with notification.", serializationEx); } catch (QueueDataError <BaseNotification> notificationEx) { eventLogRepository.WriteErrorLog("Error processing notification.", notificationEx); PublishToQueue(notificationEx.ProcessingObject, Configuration.RabbitMQNotificationErrorQueue); } catch (Exception ex) { eventLogRepository.WriteErrorLog("Unhandled error processing notification.", ex); } }
private void PublishToQueue(BaseNotification notification, string queue) { string serializedNotification = Newtonsoft.Json.JsonConvert.SerializeObject(notification); genericQueueRepository.PublishToQueue(serializedNotification, Configuration.RabbitMQNotificationServer, Configuration.RabbitMQNotificationUserNameConsumer, Configuration.RabbitMQNotificationUserPasswordPublisher, Configuration.RabbitMQVHostNotification, Configuration.RabbitMQExchangeNotificationError); }
public static BaseNotification Deserialize(string json) { using (var ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(json))) { var serializer = new DataContractJsonSerializer(typeof(BaseNotification)); BaseNotification notification = (BaseNotification)serializer.ReadObject(ms); ms.Position = 0; switch (notification.NotificationType) { case Core.Enumerations.Messaging.NotificationType.OrderConfirmation: return((BaseNotification) new DataContractJsonSerializer(typeof(OrderConfirmationNotification)).ReadObject(ms)); case Core.Enumerations.Messaging.NotificationType.Eta: return((BaseNotification) new DataContractJsonSerializer(typeof(EtaNotification)).ReadObject(ms)); case Core.Enumerations.Messaging.NotificationType.PaymentConfirmation: return((BaseNotification) new DataContractJsonSerializer(typeof(PaymentConfirmationNotification)).ReadObject(ms)); case Core.Enumerations.Messaging.NotificationType.HasNews: return((BaseNotification) new DataContractJsonSerializer(typeof(HasNewsNotification)).ReadObject(ms)); default: return(notification); } } }
public async Task SendNotification(NotificationScope scope, BaseNotification notification) { if (scope == null) { throw new ArgumentNullException(nameof(scope)); } if (notification == null) { throw new ArgumentNullException(nameof(notification)); } var users = await GetUsers(scope); using (var db = _contextFactory.CreateContext()) { foreach (var uid in users) { var obj = JsonConvert.SerializeObject(notification); var data = new NotificationData { Id = Guid.NewGuid().ToString(), Created = DateTimeOffset.UtcNow, ApplicationUserId = uid, NotificationType = GetNotificationTypeString(notification.GetType()), Blob = ZipUtils.Zip(obj), Seen = false }; db.Notifications.Add(data); } await db.SaveChangesAsync(); } }
public void OnAuthenticationFailed(IOwinContext context, BaseNotification <OpenIdConnectAuthenticationOptions> baseNotif) { OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions(); RedirectToIdentityProviderNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> redirectContext = new RedirectToIdentityProviderNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(context, options); redirectContext.HandleResponse(); baseNotif.HandleResponse(); }
public static void SendMessage(Notification notificacion) { var message = JsonConvert.SerializeObject(notificacion); var topiccrn = Environment.GetEnvironmentVariable("TOPIC_ARN"); var publication = new BaseNotification(topiccrn); publication.SendMessage("Notificaction", message); }
public async Task PublishAsync(BaseNotification notification) { _logger.LogInformation("Publish notification: {Notification}", notification.GetType().Name); var wrappedNotification = notification.Wrap(); await PublishConsoleAsync(wrappedNotification); await PublishSocketsAsync(wrappedNotification); }
/// <summary> /// Catch UI events sent from the Model. /// </summary> /// <param name="sender"></param> /// <param name="action"></param> public void ModelEventListener(Object sender, BaseNotification action) { if (action is WorkItemCreatingNotification) { Console.WriteLine("WorkItemCreatingAction in usercontrol"); SelectedTaskTitleField.Focus(); } }
private static Action GetDispatchFunc <TNotification>(BaseNotification notification, Action <TNotification> dispatch) where TNotification : BaseNotification { TNotification castedNotification = notification as TNotification; return((castedNotification != null) ? ((Action) delegate { dispatch(castedNotification); }) : null); }
public async Task <BaseNotification> UpdateNotifay(BaseNotification notifay) { Check.ArgumentNotNull(nameof(notifay), notifay); _context.Notifications.Update(notifay); await _context.SaveChangesAsync(); return(notifay); }
private void DispatchQueue() { while (queue.Count > 0 && ShouldDispatchNotification(queue[0])) { BaseNotification notification = queue[0]; queue.RemoveAt(0); DispatchNotification(notification); } }
private void ClearAndCallBackPrePauseQueue() { while (prePauseQueue.Count > 0) { BaseNotification baseNotification = prePauseQueue[0]; prePauseQueue.RemoveAt(0); this.OnDispatched(baseNotification.SequenceNumber.Value); } }
private void notify(string type, object data = null) { INotification notificaion = new BaseNotification(); notificaion.data = data; AppNotification note = new AppNotification(type, notificaion); note.dispatch(); }
public static string ToJson(this BaseNotification baseNotification) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(baseNotification.GetType()); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, baseNotification); return(Encoding.UTF8.GetString(ms.ToArray())); } }
public void notify(String typeStr, Object data = null) { BaseNotification notification = new BaseNotification(); notification.data = data; AppNotification note = new AppNotification(typeStr, notification); note.dispatch(); }
/*注册协议处理 * **/ private static void RegisterProtolHandler <C, T>(uint id) where C : GameBaseCommand, new() { Action <MemoryStream> act = (MemoryStream stream) => { T ackMsg = Serializer.Deserialize <T>(stream); BaseNotification notification = new BaseNotification(); notification.data = ackMsg; C cmd = new C(); cmd.excute(notification); }; protolHandlerMap[id] = act; }
public void Remove(BaseNotification notification) { List <BaseNotification> notificationList; _notificationDict.TryGetValue(notification.Id, out notificationList); #if UNITYR_EDITOR if (notificationList == null || notificationList.IndexOf(notification) == -1) { LogUtil.E("Could not find notification {0} in NotificationManager!", notification.ToString()); return; } #endif notificationList.Remove(notification); }
public void ProcessNotification(BaseNotification notification) { try { if (notification.NotificationType != NotificationType.OrderConfirmation) { throw new ApplicationException("notification/handler type mismatch"); } OrderConfirmationNotification orderConfirmation = (OrderConfirmationNotification)notification; // load up recipients, customer and message eventLogRepository.WriteInformationLog("order confirmation base, custNum: " + notification.CustomerNumber + ", branch: " + notification.BranchId); Customer customer = customerRepository.GetCustomerByCustomerNumber(notification.CustomerNumber, notification.BranchId); NewRelic.Api.Agent.NewRelic.AddCustomParameter("OrderNumber", orderConfirmation.OrderNumber); NewRelic.Api.Agent.NewRelic.AddCustomParameter("InvoiceNumber", orderConfirmation.InvoiceNumber); NewRelic.Api.Agent.NewRelic.AddCustomParameter("CustomerNumber", orderConfirmation.CustomerNumber); NewRelic.Api.Agent.NewRelic.AddCustomParameter("BranchId", orderConfirmation.BranchId); NewRelic.Api.Agent.NewRelic.AddCustomParameter("OrderChange.Items.Count", orderConfirmation.OrderChange.Items.Count); if (customer == null) { StringBuilder warningMessage = new StringBuilder(); warningMessage.AppendFormat("Could not find customer({0}-{1}) to send Order Confirmation notification.", notification.BranchId, notification.CustomerNumber); warningMessage.AppendLine(); warningMessage.AppendLine(); warningMessage.AppendLine("Notification:"); warningMessage.AppendLine(notification.ToJson()); eventLogRepository.WriteWarningLog(warningMessage.ToString()); } else { List <Recipient> recipients = LoadRecipients(orderConfirmation.NotificationType, customer); Message message = GetEmailMessageForNotification(orderConfirmation, customer); // send messages to providers... if (recipients != null && recipients.Count > 0) { SendMessage(recipients, message); } } } catch (Exception ex) { throw new Core.Exceptions.Queue.QueueDataError <BaseNotification>(notification, "OrderConfirmation:ProcessNotification", "Sending order confirmation", "There was an exception sending an order confirmation", ex); } }
public void Dispatch(BaseNotification notification, Action successCallback, Action failureCallback) { if (notification.SequenceNumber <= LatestSequenceNumber) { successCallback(); } else if (ShouldDispatchNotification(notification)) { this.OnQueued(notification.SequenceNumber.Value); DispatchNotification(notification); DispatchQueue(); successCallback(); } else { QueueNotification(notification); WaitForDispatchOrClear(notification.SequenceNumber.Value, successCallback, failureCallback); } }
public void Add(BaseNotification notification) { List <BaseNotification> notificationList; if (!_notificationDict.TryGetValue(notification.Id, out notificationList)) { notificationList = new List <BaseNotification>(); _notificationDict.Add(notification.Id, notificationList); } #if UNITYR_EDITOR if (notificationList.IndexOf(notification) != -1) { LogUtil.E("Notification {0} has been added to the NotificationManager!", notification.ToString()); return; } #endif notificationList.Add(notification); }
/// <summary> /// Receives events from the WorkItemJournalViewModel. /// </summary> /// <param name="sender"></param> /// <param name="notification"></param> public void ModelEventListener(Object sender, BaseNotification notification) { if (notification is WorkItemJournalCreatingNotification) { // Ensure that the Journal tab is displayed on the WorkItemUserControl Messenger.Default.Send(new WorkItemSelectTabAction(TAB_NAME)); // If desired, move the vertical split. if (((WorkItemJournalCreatingNotification)notification).GiveDetailTabProminence) { MoveVerticalSplit(SplitSetting.RIGHT_EXPANDED); } // Give the field focus JournalTitleField.Focus(); } else if (notification is MoveVerticalWorkItemJournalSplitNotification) { MoveVerticalSplit(((MoveVerticalWorkItemJournalSplitNotification)notification).VerticalSplit); } }
/// <summary> /// Process user feedback notification. /// </summary> /// <param name="notification"></param> public void ProcessNotification(BaseNotification notification) { try { if (notification.NotificationType != NotificationType.UserFeedback) { throw new ApplicationException("notification/handler type mismatch"); } UserFeedbackNotification feedbackNotification = (UserFeedbackNotification)notification; UserFeedbackContext context = feedbackNotification.Context; Message message = CreateEmailMessageForNotification(feedbackNotification); try { _emailClient.SendEmail( new List <string>() { context.TargetEmailAddress }, null, null, context.SourceEmailAddress, message.MessageSubject, message.MessageBody, message.BodyIsHtml ); } catch (Exception ex) { _eventLogRepository.WriteErrorLog("EmailMessageProvider: Error sending email", ex); } } catch (Exception ex) { throw new Core.Exceptions.Queue.QueueDataError <BaseNotification>(notification, "UserFeedback:ProcessNotification", "Sending user feedback", "There was an exception processing user feedback", ex); } }
private void ConsumeMessages() { while (consumingMessages && doListenForMessagesInTask) { string msg = ConsumeMessageFromQueue(); if (msg != null) { BaseNotification notification = NotificationExtension.Deserialize(msg); eventLogRepository.WriteInformationLog("Processing notification from queue. Notification: {QueueMessage}".InjectSingleValue("QueueMessage", msg)); var handler = notificationHandlerFactory(notification.NotificationType); // autofac will get the right handler handler.ProcessNotification(notification); // Always clear the context at the end of a transaction _uow.ClearContext(); } else { consumingMessages = false; } } }
public async Task <bool> Enqueue(BaseNotification notification, DateTime timeToSend) { var noti = new DAL.Models.Notification() { Type = notification.Type, JsonData = notification.SerializeContentToString(), TimeCreated = DateTime.UtcNow, TimeToSend = timeToSend, }; _dbContext.Notification.Add(noti); await _dbContext.SaveChangesAsync(); // nats request try { var request = new Bus.Models.Core.Sub.NotificationSendRequest() { ID = (ulong)noti.Id, }; var reply = await _bus.Request( Bus.Models.Core.Sub.Subjects.NotificationSendRequest, request, Bus.Models.Core.Sub.NotificationSendResponse.Parser ); if (!reply.Success) { _logger.Error(new Exception(reply.Error), $"Failed to request notification sending via Nats"); return(false); } } catch (Exception e) { _logger.Error(e, $"Failed to get bus connection and send notification"); return(false); } return(true); }
static void Main(string[] args) { using (NotificationContext dbContext = new NotificationContext()) { dbContext.Configuration.AutoDetectChangesEnabled = false; GenericQueueRepositoryImpl rmq = new GenericQueueRepositoryImpl(); string rmqMessage = rmq.ConsumeFromQueue(Configuration.RabbitMQNotificationServer, Configuration.RabbitMQNotificationUserNameConsumer, Configuration.RabbitMQNotificationUserPasswordConsumer, Configuration.RabbitMQVHostNotification, Configuration.RabbitMQQueueNotification); while (rmqMessage != null) { BaseNotification rmqNotification = NotificationExtension.Deserialize(rmqMessage); if (rmqNotification.NotificationType == NotificationType.Eta) { KeithLink.Svc.Core.Models.Messaging.Queue.EtaNotification eta = (KeithLink.Svc.Core.Models.Messaging.Queue.EtaNotification)rmqNotification; Console.WriteLine(string.Format("Processing {0} orders", eta.Orders.Count)); foreach (OrderEta order in eta.Orders) { Models.EtaNotification notice = new Models.EtaNotification(); if (order.ActualTime != null && order.ActualTime.Length > 0) { notice.ActualTime = DateTime.Parse(order.ActualTime); } notice.Branch = order.BranchId; if (order.EstimatedTime != null && order.EstimatedTime.Length > 0) { notice.EstimatedTime = DateTime.Parse(order.EstimatedTime); } notice.OrderId = order.OrderId; if (order.OutOfSequence.HasValue) { notice.OutOfSequence = order.OutOfSequence.Value; } notice.RouteId = order.RouteId; if (order.ScheduledTime != null && order.ScheduledTime.Length > 0) { notice.ScheduledTime = DateTime.Parse(order.ScheduledTime); } notice.StopNumber = order.StopNumber; dbContext.Notifications.Add(notice); dbContext.SaveChanges(); } // end foreach } // end if rmqMessage = rmq.ConsumeFromQueue(Configuration.RabbitMQNotificationServer, Configuration.RabbitMQNotificationUserNameConsumer, Configuration.RabbitMQNotificationUserPasswordConsumer, Configuration.RabbitMQVHostNotification, Configuration.RabbitMQQueueNotification); } // wend if (dbContext.Database.Connection.State == System.Data.ConnectionState.Open) { dbContext.Database.Connection.Close(); } } //end using }
private static bool Validate(BaseNotification notification) { return(notification != null && notification.SequenceNumber.HasValue && notification.SequenceNumber != 0); }
public static INotification Wrap(this BaseNotification notification) { var genericType = typeof(WrapperNotification <>).MakeGenericType(notification.GetType()); return((Activator.CreateInstance(genericType, notification) as INotification) !); }
public void ProcessNotification(BaseNotification notification) { try { if (notification.NotificationType != NotificationType.PaymentConfirmation) { throw new ApplicationException("notification/handler type mismatch"); } // had to setup a translation for this type in Svc.Core.Extensions to deserialize the message with the concrete type PaymentConfirmationNotification confirmation = (PaymentConfirmationNotification)notification; // UserContextEqualityComparer discriminates usercontext's to allow distinct to weed out duplicates List <UserSelectedContext> customerCtxs = confirmation.Payments .Select(p => new UserSelectedContext() { CustomerId = p.CustomerNumber, BranchId = p.BranchId }) .Distinct(new UserContextEqualityComparer()) .ToList(); bool complexPayment = customerCtxs.Count > 1; string payerEmail = confirmation.SubmittedBy; List <Recipient> payerRecipient = null; foreach (UserSelectedContext customerCtx in customerCtxs) { // load up recipients, customer and message Svc.Core.Models.Profile.Customer customer = _customerRepo.GetCustomerByCustomerNumber(customerCtx.CustomerId, customerCtx.BranchId); if (customer == null) { StringBuilder warningMessage = new StringBuilder(); warningMessage.AppendFormat("Could not find customer({0}-{1}) to send Payment Confirmation notification.", customerCtx.BranchId, customerCtx.CustomerId); warningMessage.AppendLine(); warningMessage.AppendLine(); warningMessage.AppendLine("Notification:"); warningMessage.AppendLine(notification.ToJson()); _log.WriteWarningLog(warningMessage.ToString()); } else { List <Recipient> recipients = LoadRecipients(confirmation.NotificationType, customer); Message message = GetEmailMessageForNotification(confirmation.Payments .Where(p => p.CustomerNumber == customerCtx.CustomerId && p.BranchId == customerCtx.BranchId) .ToList(), customer); // send messages to providers... if (recipients != null && recipients.Count > 0) { if (complexPayment) // mask out payeremail recipient from the regular recipients { payerRecipient = recipients.Where(r => r.UserEmail.ToLower() == payerEmail.ToLower()).ToList(); recipients = recipients.Where(r => r.UserEmail.ToLower() != payerEmail.ToLower()).ToList(); } if (recipients.Count > 0) { SendMessage(recipients, message); } } } } if (complexPayment && payerRecipient != null) { SendMessage(payerRecipient, GetEmailMessageForMultipleAccountSummaryNotification(confirmation.Payments, customerCtxs)); } } catch (Exception ex) { throw new Core.Exceptions.Queue.QueueDataError <BaseNotification>(notification, "PaymentConfirmation:ProcessNotification", "Sending PaymentConfirmation notification", "An error occured processing a payment confirmation", ex); } }