public void Should_return_true_if_Messages_contains_only_messages_with_Info_Severity()
 {
     var notification = new Notification();
     var messageTest = new NotificationMessage(NotificationSeverity.Info, "");
     notification.Add(messageTest);
     Assert.IsTrue(notification.IsValid);
 }
        void INotificationChannel.Notify(NotificationMessage notificationMessage)
        {
            if (Observer != null)
                notificationMessage.InvokePayload.Invoke(Observer);

            if (Messages != null)
                Messages.Add(notificationMessage);
        }
        public void get_message_with_substitutions()
        {
            var message = new NotificationMessage(NotificationMessageKeys.SUBSTITUTE_NAME_AND_AGE)
                .AddSubstitution("Name", "Max")
                .AddSubstitution("Age", "7");

            message.GetMessage().ShouldEqual("Max is 7 years old");
        }
            public void Should_return_false_if_Messages_contains_only_messages_with_Warning_Severity()
            {
                var notification = new Notification();
                var messageTest = new NotificationMessage(NotificationSeverity.Warning, "");
                notification.Add(messageTest);

                Assert.IsFalse(notification.IsValid);
            }
 public void Publish(NotificationMessage message)
 {
     Task.Delay(message.millis).ContinueWith((antecedent) => {
         foreach (var connection in _subscribers){
             Clients.Client(connection).notification(message.message);
         }
     });
 }
 public static ValidationStrategyResult Invalid(NotificationMessage message)
 {
     return new ValidationStrategyResult
                {
                    IsValid = false,
                    Message = message
                };
 }
 public void Should_return_the_formatted_value_that_was_passed_in_the_constructor_if_a_format_string_was_used()
 {
     const string format = "test {0} now {1}";
     const int arg0 = 1;
     const string arg1 = "help";
     var message = new NotificationMessage(NotificationSeverity.Warning, format, arg0, arg1);
     Assert.AreEqual(String.Format(format, arg0, arg1), message.Message);
 }
Example #8
0
        private void HandleNotificationMessage(NotificationMessage message)
        {
            if (message == null) return;

              if (message.Notification == UIMessageType.Common_CloseWindowEvent)
              {
            this.Close();
              }
        }
 protected override void OnNotificationMessage(NotificationMessage message)
 {
     SendPacket(new Packet
     {
         Type = PacketType.Notification,
         ActorId = message.ObserverId,
         RequestId = message.NotificationId,
         Message = message.InvokePayload,
     });
 }
        public void equality_check_negative()
        {
            var token = StringToken.FromKeyString("Test", "1...2...3");
            var v1 = TemplateValue.For("FirstName", "Joel");
            var v2 = TemplateValue.For("LastName", "Arnold");

            var message1 = new NotificationMessage(token, v1, v2);
            var message2 = new NotificationMessage(token, v1);

            message1.ShouldNotEqual(message2);
        }
        public void NotificationMessage_Equality()
        {
            var notificationMessage1 = new NotificationMessage("propertyName1", "errorMessage1");
            var notificationMessage2 = new NotificationMessage("propertyName1", "errorMessage1");
            var notificationMessage3 = new NotificationMessage("propertyName3", "errorMessage3");

            Assert.AreEqual(notificationMessage1, notificationMessage2);
            Assert.AreNotEqual(notificationMessage1, notificationMessage3);
            Assert.IsTrue(notificationMessage1 == notificationMessage2);
            Assert.IsTrue(notificationMessage1 != notificationMessage3);
        }
Example #12
0
            public void Should_copy_the_NotificationMessages_from_the_source_if_the_destination_is_not_Notification_Null()
            {
                var source = new Notification();
                var notification = new NotificationMessage(NotificationSeverity.Error, "");
                source.Add(notification);

                var destination = new Notification();
                destination.Add(notification);

                Assert.AreEqual(1, destination.Messages.Count());
                Assert.AreEqual(notification, destination.Messages.First());
            }
        public void ProcessFeed()
        {
            try
            {
                _logger.Log("ProcessFeed() called...", LogCategory.Information);

                using (var rss = new RssReader(ConfigurationManager.AppSettings["FeedUrl"]))
                {
                    var items = rss.Execute().ToList();
                    var newNofication = new List<RssItem>();

                    if(items.Count <= 0)
                        return;

                    try
                    {
                        using (IDataContext dataContext = _dataContextFactory.Create(ConnectionType.Ip))
                        {
                            var notifications = dataContext.Query<NotificationMessage>().ToList();

                            newNofication.AddRange(notifications.Any()
                                ? items.Where(rssItem => notifications.All(n => n.StartDate != rssItem.Date))
                                : items);

                            foreach (var rssNotification in newNofication)
                            {
                                var notification = new NotificationMessage
                                {
                                    Text = rssNotification.Title,
                                    Link = rssNotification.Link,
                                    StartDate = rssNotification.Date,
                                    EndDate = rssNotification.ExpireOn,
                                    NotificationId = Guid.NewGuid()
                                };

                                dataContext.Add(notification);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogException(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
        public void prepend_property()
        {
            var message = new NotificationMessage(ValidationKeys.Required);
            message.AddAccessor(ReflectionHelper.GetAccessor<ContactModel>(x => x.FirstName));
            message.AddAccessor(ReflectionHelper.GetAccessor<ContactModel>(x => x.LastName));

            var property = ReflectionHelper.GetAccessor<CompositeModel>(x => x.Contact);

            var prepended = message.Prepend(property);

            prepended.ShouldNotBeTheSameAs(message);
            prepended.Accessors.Select(x => x.Name).ShouldHaveTheSameElementsAs("ContactFirstName", "ContactLastName");
            prepended.StringToken.ShouldEqual(ValidationKeys.Required);
        }
	        public void Validate(Accessor accessor, ValidationContext context)
            {
                var username = context.GetFieldValue<string>(accessor);
                var userService = context.Service<IUserService>();
                
                if (userService.ExistsByUsername(username))
                {
                    var token = new ValidationKeys("Username {0} is already in use.".ToFormat(FIELD.AsTemplateField()));
                    var msg = new NotificationMessage(token);
                    msg.AddSubstitution(FIELD, username);

                    context.Notification.RegisterMessage(accessor, msg);
                }
            }
        public void to_validation_error_if_multiple_accessors_match_a_message()
        {
            var notification = new Notification();
            var token = StringToken.FromKeyString("test1", "test1");
            var message = new NotificationMessage(token);
            message.AddAccessor(ReflectionHelper.GetAccessor<EntityToValidate>(x => x.Something));
            message.AddAccessor(ReflectionHelper.GetAccessor<EntityToValidate>(x => x.Else));

            notification.RegisterMessage(message);

            var errors = notification.ToValidationErrors();
            errors.Length.ShouldEqual(2);

            errors.Each(x => x.message.ShouldEqual("test1"));

            errors.First().field.ShouldEqual("Something");
            errors.Last().field.ShouldEqual("Else");
        }
Example #17
0
 protected abstract Task Send(NotificationMessage model, T settings);
Example #18
0
 public void Notify(NotificationMessage message)
 {
     EmailManager.Current.SendEmail(message);
 }
Example #19
0
        /// <summary>
        /// Processes the response from a publish request.
        /// </summary>
        private void ProcessPublishResponse(
            ResponseHeader      responseHeader,
            uint                subscriptionId,
            UInt32Collection    availableSequenceNumbers,
            bool                moreNotifications,
            NotificationMessage notificationMessage)
        {
            Subscription subscription = null;
            
            // send notification that the server is alive.
            OnKeepAlive(m_serverState, responseHeader.Timestamp);

            // collect the current set if acknowledgements.
            lock (SyncRoot)
            {
                // clear out acknowledgements for messages that the server does not have any more.
                SubscriptionAcknowledgementCollection acknowledgementsToSend = new SubscriptionAcknowledgementCollection();

                for (int ii = 0; ii < m_acknowledgementsToSend.Count; ii++)
                {
                    SubscriptionAcknowledgement acknowledgement = m_acknowledgementsToSend[ii];

                    if (acknowledgement.SubscriptionId != subscriptionId)
                    {
                        acknowledgementsToSend.Add(acknowledgement);
                    }
                    else
                    {
                        if (availableSequenceNumbers == null || availableSequenceNumbers.Contains(acknowledgement.SequenceNumber))
                        {
                            acknowledgementsToSend.Add(acknowledgement);
                        }
                    }
                }

                // create an acknowledgement to be sent back to the server.
                if (notificationMessage.NotificationData.Count > 0)
                {
                    SubscriptionAcknowledgement acknowledgement = new SubscriptionAcknowledgement();

                    acknowledgement.SubscriptionId = subscriptionId;
                    acknowledgement.SequenceNumber = notificationMessage.SequenceNumber;

                    acknowledgementsToSend.Add(acknowledgement);
                }

                uint lastSentSequenceNumber = 0;
                if (availableSequenceNumbers != null)
                {
                    foreach (uint availableSequenceNumber in availableSequenceNumbers)
                    {
                        if (m_latestAcknowledgementsSent.ContainsKey(subscriptionId))
                        {
                            lastSentSequenceNumber = m_latestAcknowledgementsSent[subscriptionId];

                            // If the last sent sequence number is uint.Max do not display the warning; the counter rolled over
                            // If the last sent sequence number is greater or equal to the available sequence number (returned by the publish), a warning must be logged.
                            if (((lastSentSequenceNumber >= availableSequenceNumber) && (lastSentSequenceNumber != uint.MaxValue)) || (lastSentSequenceNumber == availableSequenceNumber) && (lastSentSequenceNumber == uint.MaxValue))
                            {
                                Utils.Trace("Received sequence number which was already acknowledged={0}", availableSequenceNumber);
                            }
                        }
                    }
                }

                if (m_latestAcknowledgementsSent.ContainsKey(subscriptionId))
                {
                    lastSentSequenceNumber = m_latestAcknowledgementsSent[subscriptionId];

                    // If the last sent sequence number is uint.Max do not display the warning; the counter rolled over
                    // If the last sent sequence number is greater or equal to the notificationMessage's sequence number (returned by the publish), a warning must be logged.
                    if (((lastSentSequenceNumber >= notificationMessage.SequenceNumber) && (lastSentSequenceNumber != uint.MaxValue)) || (lastSentSequenceNumber == notificationMessage.SequenceNumber) && (lastSentSequenceNumber == uint.MaxValue))
                    {
                        Utils.Trace("Received sequence number which was already acknowledged={0}", notificationMessage.SequenceNumber);
                    }
                }

                if (availableSequenceNumbers != null)
                {
                    foreach (var acknowledgement in acknowledgementsToSend)
                    {
                        if (acknowledgement.SubscriptionId == subscriptionId && !availableSequenceNumbers.Contains(acknowledgement.SequenceNumber))
                        {
                            Utils.Trace("Sequence number={0} was not received in the available sequence numbers.", acknowledgement.SequenceNumber);
                        }
                    }
                }

                m_acknowledgementsToSend = acknowledgementsToSend;

                if (notificationMessage.IsEmpty)
                {
                    Utils.Trace("Empty notification message received for SessionId {0} with PublishTime {1}", SessionId, notificationMessage.PublishTime.ToLocalTime());
                }

                // find the subscription.
                foreach (Subscription current in m_subscriptions)
                {
                    if (current.Id == subscriptionId)
                    {
                        subscription = current;                            
                        break;
                    }
                }                    
            }

            // ignore messages with a subscription that has been deleted.
            if (subscription != null)
            {
                // Validate publish time and reject old values.
                if (notificationMessage.PublishTime.AddMilliseconds(subscription.CurrentPublishingInterval * subscription.CurrentLifetimeCount) < DateTime.UtcNow)
                {
                    Utils.Trace("PublishTime {0} in publish response is too old for SubscriptionId {1}.", notificationMessage.PublishTime.ToLocalTime(), subscription.Id);
                }

                // Validate publish time and reject old values.
                if (notificationMessage.PublishTime > DateTime.UtcNow.AddMilliseconds(subscription.CurrentPublishingInterval * subscription.CurrentLifetimeCount))
                {
                    Utils.Trace("PublishTime {0} in publish response is newer than actual time for SubscriptionId {1}.", notificationMessage.PublishTime.ToLocalTime(), subscription.Id);
                }

                // update subscription cache.                                 
                subscription.SaveMessageInCache(
                    availableSequenceNumbers, 
                    notificationMessage, 
                    responseHeader.StringTable);

                // raise the notification.
                lock (m_eventLock)
                {
                    NotificationEventArgs args = new NotificationEventArgs(subscription, notificationMessage, responseHeader.StringTable);

                    if (m_Publish != null)
                    {
                        ThreadPool.QueueUserWorkItem(OnRaisePublishNotification, args);
                    }
                }
            }
            else
            {
                Utils.Trace("Received Publish Response for Unknown SubscriptionId={0}", subscriptionId);
            }
        }
Example #20
0
        protected override void ExecuteLogic()
        {
            // get the triggering record
            var target = Target;
            NotificationMessage message = null;

            var isEnabled = CrmHelpers
                            .GetGenericConfig(Service, Context.OrganizationId).ToEntity <CommonConfiguration>()?
                            .NotificationsCentreEnabled == true;

            if (!isEnabled)
            {
                return;
            }

            switch (target.LogicalName)
            {
            case Email.EntityLogicalName:
                var email = target.ToEntity <Email>();
                var body  = email.Description;

                // no message
                if (string.IsNullOrEmpty(body))
                {
                    return;
                }

                if (body.Contains("<html>"))
                {
                    var doc = new XmlDocument();
                    doc.LoadXml(body);
                    body = doc.SelectSingleNode("body")?.InnerXml;
                }

                // html has no body to display
                if (string.IsNullOrEmpty(body))
                {
                    return;
                }

                var users = email.To
                            .Select(e => e.Party)
                            .Where(a => a.LogicalName == User.EntityLogicalName)
                            .Select(a =>
                                    new NotificationMessageUser
                {
                    User = a.Id
                }).ToArray();

                // no users to notify
                if (!users.Any())
                {
                    return;
                }

                message =
                    new NotificationMessage
                {
                    Title              = email.Subject,
                    Message            = body,
                    RegardingTypeCode  = Email.EntityTypeCode,
                    RegardingID        = target.Id.ToString(),
                    MessageUsers       = users,
                    NotificationSource = GlobalEnums.NotificationSource.Email
                };

                break;

            case Task.EntityLogicalName:
                var task = target.ToEntity <Task>();
                message =
                    new NotificationMessage
                {
                    Title             = task.Subject,
                    Message           = task.Description,
                    RegardingTypeCode = Task.EntityTypeCode,
                    RegardingID       = target.Id.ToString()
                };

                var owner = task.Owner;

                switch (owner.LogicalName)
                {
                case User.EntityLogicalName:
                    message.MessageUsers =
                        new[]
                    {
                        new NotificationMessageUser
                        {
                            User = owner.Id
                        }
                    };
                    break;

                case Team.EntityLogicalName:
                    message.MessageTeams =
                        new[]
                    {
                        new NotificationMessageTeam
                        {
                            Team = owner.Id
                        }
                    };
                    break;
                }

                message.NotificationSource = GlobalEnums.NotificationSource.Task;

                break;
            }

            if (message != null)
            {
                message.StatusReason = NotificationMessage.StatusReasonEnum.Open;
                Service.Create(message);
            }
        }
Example #21
0
        private void ReplyToMessage(NotificationMessage msg)
        {
            Window win = null;

            if (!(msg.Target is SendType))
            {
                return;
            }
            switch ((SendType)msg.Target)
            {
            case SendType.DoScrollHome:
            {
                this.sv.ScrollToHome();
                return;
            }

            case SendType.ResetScroll:
            {
                this.ot.VerticalOffset = double.NaN;
                this.ot.Time           = System.DateTime.Now;
                return;
            }

            case SendType.DoScrollLineDown:
            {
                if (this.ot.VerticalOffset != this.sv.ContentVerticalOffset)
                {
                    this.sv.LineDown();
                    this.ot.VerticalOffset = this.sv.ContentVerticalOffset;
                    this.ot.Time           = System.DateTime.Now;
                }
                else
                {
                    if ((System.DateTime.Now - this.ot.Time) > System.TimeSpan.FromMilliseconds(500))
                    {
                        // page down
                        Messenger.Default.Send <NotificationMessage>(new NotificationMessage(this, SendType.DoScrollPageDown, "DoScroll"));
                    }
                }

                return;
            }

            case SendType.DoScrollLineUp:
            {
                if (this.ot.VerticalOffset != this.sv.ContentVerticalOffset)
                {
                    this.sv.LineUp();
                    this.ot.VerticalOffset = this.sv.ContentVerticalOffset;
                    this.ot.Time           = System.DateTime.Now;
                }
                else
                {
                    if ((System.DateTime.Now - this.ot.Time) > System.TimeSpan.FromMilliseconds(500))
                    {
                        // page up
                        Messenger.Default.Send <NotificationMessage>(new NotificationMessage(this, SendType.DoScrollPageUp, "DoScroll"));
                    }
                }

                return;
            }

            case SendType.OpenAboutReq:
            {
                win = new AboutWindow();
                break;
            }

            case SendType.OpenFileReq:
            {
                DoOpenFile();
                return;
            }

            case SendType.OpenSettingsReq:
            {
                win = new SettingsWindow();
                break;
            }

            case SendType.LoadFinished:
            {
                return;
            }

            case SendType.OpenPopup:
            {
                var   transform        = this.menuButton.TransformToVisual(this as FrameworkElement);
                Point absolutePosition = transform.Transform(new Point(0, 0));
                win       = new PopupWindow();
                win.Owner = this;
                win.Icon  = this.Icon;
                win.Left  = absolutePosition.X + this.menuButton.Width;
                win.Top   = absolutePosition.Y;
                win.Show();
                return;
            }

            case SendType.FocusListBox:
            {
                this.listBox1.Focus();
                return;
            }

            case SendType.ShowMessage:
            {
                win = new MessageWindow();
                break;
            }
            }


            if (win != null)
            {
                win.Icon  = this.Icon;
                win.Owner = this;
                win.ShowDialog();
            }
        }
Example #22
0
 private void OnSetDuplicatePath(NotificationMessage message)
 {
     DuplicateCheckDirectories.Add(message.Notification);
 }
Example #23
0
 private void NotificationMessageReceived(NotificationMessage msg)
 {
     //If this is not the intended target
     if (msg.Target != null && msg.Target != this)
     {
         return;
     }
     if (msg.Notification == "OpenFocusTree")
     {
         FocusGridModel container = msg.Sender as FocusGridModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "OpenLocalisation")
     {
         LocalisationModel container = msg.Sender as LocalisationModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "OpenEventList")
     {
         EventTabModel container = msg.Sender as EventTabModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "OpenScriptList")
     {
         ScriptModel container = msg.Sender as ScriptModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "SaveProject")
     {
         saveProject();
     }
     if (msg.Notification == "RefreshProjectViewer")
     {
         TabsModelList.Clear();
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "SendDeleteItemSignal")
     {
         ObservableObject Model = null;
         if (msg.Sender is FocusGridModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is FocusGridModel &&
                                                  ((FocusGridModel)m).UniqueID == ((FocusGridModel)msg.Sender).UniqueID);
         }
         else if (msg.Sender is LocalisationModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is LocalisationModel &&
                                                  ((LocalisationModel)m).UniqueID == ((LocalisationModel)msg.Sender).UniqueID);
         }
         else if (msg.Sender is EventTabModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is EventTabModel &&
                                                  ((EventTabModel)m).UniqueID == ((EventTabModel)msg.Sender).UniqueID);
         }
         else if (msg.Sender is ScriptModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is ScriptModel &&
                                                  ((ScriptModel)m).UniqueID == ((ScriptModel)msg.Sender).UniqueID);
         }
         TabsModelList.Remove(Model);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Target == this)
     {
         //Resend to the tutorial View model if this was the target
         Messenger.Default.Send(new NotificationMessage(msg.Sender,
                                                        new ViewModelLocator().Tutorial, msg.Notification));
     }
 }
Example #24
0
        public void get_message_without_subsitutions()
        {
            var message = new NotificationMessage(NotificationMessageKeys.NO_SUBSTITUTION);

            message.GetMessage().ShouldEqual(NotificationMessageKeys.NO_SUBSTITUTION.ToString());
        }
Example #25
0
        private void SendNotification(NotificationMessage notification, string socketId)
        {
            var message = JsonConvert.SerializeObject(notification, JsonSettings.Setttings);

            _sender.Send(socketId, message);
        }
Example #26
0
        private void NotificationMessageReceived(NotificationMessage msg)
        {
            if (msg.Notification == "ShowGcodeEditor")
            {
                try
                {
                    var type = msg.Sender.GetType();

                    IList items      = (System.Collections.IList)msg.Sender;
                    var   collection = items.Cast <GCode>();
                    ObservableCollection <GCode> gcodes = new ObservableCollection <GCode>(collection);

                    GcodeViewerWindow viewer = new GcodeViewerWindow(gcodes);
                    viewer.Owner = Application.Current.MainWindow;
                    viewer.Show();
                }
                catch (Exception exc)
                {
                }
            }
            else if (msg.Notification == "ResetCameraGcode")
            {
                try
                {
                    // Helix.Wpf
                    //view2dGcode.Camera.Reset();
                    //view2dGcode.Camera.ZoomExtents(view2dGcode.Viewport, 1);
                }
                catch (Exception exc)
                {
                }
            }
            else if (msg.Notification == "ResetCameraGcode3d")
            {
                try
                {
                    view3dGcode.Camera.Reset();
                    view3dGcode.Camera.ZoomExtents(view3dGcode, 1);
                    // Helix.Wpf
                    //view3dGcode.Camera.Reset();
                    //view3dGcode.Camera.ZoomExtents(view3dGcode.Viewport, 1);
                }
                catch (Exception exc)
                {
                }
            }
            else if (msg.Notification == "ResetCameraStl")
            {
                try
                {
                    view3d.Camera.Reset();
                    view3d.Camera.ZoomExtents(view3d, 1);
                    // Helix.Wpf
                    //view3d.Camera.Reset();
                    //view3d.Camera.ZoomExtents(view3d.Viewport);
                }
                catch (Exception exc)
                {
                }
            }
            else if (msg.Notification == "ZoomToFitGcode")
            {
                try
                {
                    view2dGcode.Camera.ZoomExtents(view2dGcode, 1);
                    // Helix.Wpf
                    //var type = msg.Sender.GetType();
                    //view2dGcode.Camera.ZoomExtents(view2dGcode.Viewport, 1);
                }
                catch (Exception exc)
                {
                }
            }
            else if (msg.Notification == "ZoomToFitStl")
            {
                try
                {
                    var type = msg.Sender.GetType();
                    view3d.Camera.ZoomExtents(view3d, 1);
                    // Helix.Wpf
                    //.Camera.ZoomExtents(view3d.Viewport);
                }
                catch (Exception exc)
                {
                }
            }
        }
Example #27
0
        /// <summary>
        /// This will load up the Email template and generate the HTML
        /// </summary>
        /// <param name="model"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public async Task SendAdHoc(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                var email = new EmailBasicTemplate();

                var customization = await CustomizationSettings.GetSettingsAsync();

                var html = email.LoadTemplate(model.Subject, model.Message, null, customization.Logo);

                var textBody = string.Empty;

                model.Other.TryGetValue("PlainTextBody", out textBody);
                var body = new BodyBuilder
                {
                    HtmlBody = html,
                    TextBody = textBody
                };

                var message = new MimeMessage
                {
                    Body    = body.ToMessageBody(),
                    Subject = model.Subject
                };
                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                message.To.Add(new MailboxAddress(model.To, model.To));

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        // Disable validation of the certificate associated with the SMTP service
                        // Helpful when the TLS certificate is not in the certificate store of the server
                        // Does carry the risk of man in the middle snooping
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        // Does not attempt to use either TLS or SSL
                        // Helpful when MailKit finds a TLS certificate, but it unable to use it
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    //Log.Info("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                //Log.Error(e);
                throw new InvalidOperationException(e.Message);
            }
        }
Example #28
0
 protected override async Task Send(NotificationMessage model, EmailNotificationSettings settings)
 {
     await EmailProvider.Send(model, settings);
 }
Example #29
0
 public void NotifyMe(NotificationMessage notificationMessage)
 {
     string notification = notificationMessage.Notification;
     //do your work
 }
 internal unsafe ConnectEventArgs(AMDeviceNotificationCallbackInfo cbi)
 {
     this.message = cbi.msg;
     this.device  = cbi.dev;
 }
Example #31
0
 private void CleanUpView(NotificationMessage message)
 {
     Messenger.Default.Unregister <NotificationMessage>(this);
 }
Example #32
0
 private void NotifyUserMethod(NotificationMessage message)
 {
     //MessageBox.Show(message.Notification);
 }
 public ItemData(
     Subscription        subscription,
     NotificationMessage notificationMessage)
 {
     Subscription        = subscription;
     NotificationMessage = notificationMessage;
 }
Example #34
0
 protected override void OnNotificationMessage(NotificationMessage message)
 {
 }
Example #35
0
        private bool updateEntityFromUI()
        {
            try
            {
                grupa.Naziv    = txtNaziv.Text.Trim();
                grupa.EngNaziv = txtEngNaziv.Text.Trim();
                if (!grupa.validate())
                {
                    return(false);
                }

                GrupaDAO grupaDAO = DAOFactoryFactory.DAOFactory.GetGrupaDAO();
                if (editMode)
                {
                    if (grupa.Naziv != oldNaziv || grupa.EngNaziv != oldEngNaziv)
                    {
                        grupaDAO.MakePersistent(grupa);
                        NHibernateHelper.GetCurrentSession().Transaction.Commit();
                        oldNaziv    = grupa.Naziv;
                        oldEngNaziv = grupa.EngNaziv;
                    }
                }
                else
                {
                    grupaDAO.MakePersistent(grupa);
                    NHibernateHelper.GetCurrentSession().Transaction.Commit();
                    grupe.Add(grupa);
                    editMode    = true;
                    oldNaziv    = grupa.Naziv;
                    oldEngNaziv = grupa.EngNaziv;
                }
                return(true);
            }
            catch (InvalidPropertyException ex)
            {
                MessageDialogs.showMessage(ex.Message, this.Text);
                setFocus(ex.InvalidProperty);
                return(false);
            }
            catch (BusinessException ex)
            {
                if (ex.Notification != null)
                {
                    NotificationMessage msg = ex.Notification.FirstMessage;
                    MessageDialogs.showMessage(msg.Message, this.Text);
                    setFocus(msg.FieldName);
                }
                else
                {
                    MessageDialogs.showMessage(ex.Message, this.Text);
                }
                return(false);
            }
            catch (InfrastructureException ex)
            {
                MessageDialogs.showMessage(ex.Message, this.Text);
                return(false);
            }
            catch (Exception ex)
            {
                MessageDialogs.showMessage(
                    Strings.getFullDatabaseAccessExceptionMessage(ex.Message), this.Text);
                return(false);
            }
        }
Example #36
0
        private void NotifyMe(NotificationMessage message)
        {
            switch (message.Notification)
            {
            case nameof(UpdatePlacementView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <UpdatePlacementView_ViewModel>();
                break;

            case nameof(UpdateCompanyDetailsView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <UpdateCompanyDetailsView_ViewModel>();
                break;

            case nameof(CompanyDetailsView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <CompanyDetailsView_ViewModel>();
                break;

            case nameof(AddSession_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <AddSession_ViewModel>();
                break;

            case nameof(IndividualCandidateDetailsView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <IndividualCandidateDetailsView_ViewModel>();
                break;

            case nameof(SessionsView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <SessionsView_ViewModel>();
                break;

            case nameof(OpeningsView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <OpeningsView_ViewModel>();
                break;

            case nameof(CandidateView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <CandidateView_ViewModel>();
                break;

            case nameof(CourseView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <CourseView_ViewModel>();

                break;

            case nameof(CompaniesView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <CompaniesView_ViewModel>();

                break;

            case nameof(PlacementsView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <PlacementsView_ViewModel>();

                break;

            case nameof(AddCandidateViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <AddCandidateViewModel>();

                break;

            case nameof(AddCompanyViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <AddCompanyViewModel>();

                break;

            case nameof(AddCourseViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <AddCourseViewModel>();

                break;

            case nameof(AddOpeningViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <AddOpeningViewModel>();

                break;

            case nameof(CandidateQualifiedForOpeningViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <CandidateQualifiedForOpeningViewModel>();

                break;

            case nameof(SessionAttendanceView_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <SessionAttendanceView_ViewModel>();

                break;

            case nameof(UpdateCandidateview_ViewModel):
                CurrentVM = CommonServiceLocator.ServiceLocator.Current.GetInstance <UpdateCandidateview_ViewModel>();

                break;
            }
        }
Example #37
0
 public void Execute(NotificationMessage notificationMessage)
 {
     _taskbar.Flash();
 }
        public string PutNotificationMessage(NotificationMessageDisplay message)
        {
            try
            {
                var provider = _notificationContext.GetProviderByMethodKey(message.MethodKey);

                var method = provider.GetNotificationGatewayMethodByKey(message.MethodKey);

                var notificationMessage = new NotificationMessage(message.MethodKey, message.Name, message.FromAddress)
                                              {
                                                  BodyTextIsFilePath
                                                      =
                                                      message
                                                      .BodyTextIsFilePath
                                              };
                method.SaveNotificationMessage(message.ToNotificationMessage(notificationMessage));

                return notificationMessage.Key.ToString();
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("{0}", ex.Message)));
            }
        }
Example #39
0
 protected override Task Send(NotificationMessage model, MobileNotificationSettings settings)
 {
     throw new NotImplementedException();
 }
Example #40
0
        /// <summary>
        /// Returns all available notifications.
        /// </summary>
        private NotificationMessage InnerPublish(
            OperationContext      context, 
            out UInt32Collection  availableSequenceNumbers, 
            out bool              moreNotifications)
        {   
            // check session.
            VerifySession(context);

            // TraceState("PUBLISH");

            // check if a keep alive should be sent if there is no data.
            bool keepAliveIfNoData = (m_keepAliveCounter >= m_maxKeepAliveCount);

            availableSequenceNumbers = new UInt32Collection();

            moreNotifications = false;

            if (m_lastSentMessage < m_sentMessages.Count)
            {
                // return the available sequence numbers.
                for (int ii = 0; ii <= m_lastSentMessage && ii < m_sentMessages.Count; ii++)
                {
                    availableSequenceNumbers.Add(m_sentMessages[ii].SequenceNumber);
                }
                
                moreNotifications = m_waitingForPublish = m_lastSentMessage < m_sentMessages.Count-1;

                // TraceState("PUBLISH QUEUED MESSAGE");
                return m_sentMessages[m_lastSentMessage++];
            }
            
            List<NotificationMessage> messages = new List<NotificationMessage>();

            if (m_publishingEnabled)
            {                
                DateTime start1 = DateTime.UtcNow;

                // collect notifications to publish.
                Queue<EventFieldList> events = new Queue<EventFieldList>();
                Queue<MonitoredItemNotification> datachanges = new Queue<MonitoredItemNotification>();
                Queue<DiagnosticInfo> datachangeDiagnostics = new Queue<DiagnosticInfo>();
                
                // check for monitored items that are ready to publish.
                LinkedListNode<IMonitoredItem> current = m_itemsToPublish.First;
                
                while (current != null)
                {
                    LinkedListNode<IMonitoredItem> next = current.Next;
                    IMonitoredItem monitoredItem = current.Value;

                    if ((monitoredItem.MonitoredItemType & MonitoredItemTypeMask.DataChange) != 0)
                    {
                        ((IDataChangeMonitoredItem)monitoredItem).Publish(context, datachanges, datachangeDiagnostics);
                    }
                    else
                    {
                        ((IEventMonitoredItem)monitoredItem).Publish(context, events);                        
                    }

                    // add back to list to check.
                    m_itemsToPublish.Remove(current);
                    m_itemsToCheck.AddLast(current);
                                    
                    // check there are enough notifications for a message.
                    if (m_maxNotificationsPerPublish > 0 && events.Count + datachanges.Count > m_maxNotificationsPerPublish)
                    {
                        // construct message.
                        int notificationCount;
                        int eventCount = events.Count;
                        int dataChangeCount = datachanges.Count;
                                           
                        NotificationMessage message = ConstructMessage(
                             events, 
                             datachanges, 
                             datachangeDiagnostics, 
                             out notificationCount);

                        // add to list of messages to send.
                        messages.Add(message);

                        lock (m_diagnostics)
                        {
                            m_diagnostics.DataChangeNotificationsCount += (uint)(dataChangeCount - datachanges.Count);
                            m_diagnostics.EventNotificationsCount += (uint)(eventCount - events.Count);
                            m_diagnostics.NotificationsCount += (uint)notificationCount;
                        }
                    }
                                        
                    current = next;
                }
                    
                // pubish the remaining notifications.
                while (events.Count + datachanges.Count > 0)
                {
                    // construct message.
                    int notificationCount;
                    int eventCount = events.Count;
                    int dataChangeCount = datachanges.Count;   
                                       
                     NotificationMessage message = ConstructMessage(
                         events, 
                         datachanges, 
                         datachangeDiagnostics, 
                         out notificationCount);

                    // add to list of messages to send.
                    messages.Add(message);

                    lock (m_diagnostics)
                    {
                        m_diagnostics.DataChangeNotificationsCount += (uint)(dataChangeCount - datachanges.Count);
                        m_diagnostics.EventNotificationsCount += (uint)(eventCount - events.Count);
                        m_diagnostics.NotificationsCount += (uint)notificationCount;
                    }
                }

                // check for missing notifications.
                if (!keepAliveIfNoData && messages.Count == 0)
                {
                    Utils.Trace(
                        (int)Utils.TraceMasks.Error,
                        "Oops! MonitoredItems queued but no notifications availabled.");
               
                    m_waitingForPublish = false;

                    return null;
                }
                
                DateTime end1 = DateTime.UtcNow;
                
                double delta1 = ((double)(end1.Ticks-start1.Ticks))/TimeSpan.TicksPerMillisecond;

                if (delta1 > 200)
                {
                    TraceState(Utils.Format("PUBLISHING DELAY ({0}ms)", delta1));
                }
            }

            if (messages.Count == 0)
            {
                // create a keep alive message.
                NotificationMessage message = new NotificationMessage();

                // use the sequence number for the next message.                    
                message.SequenceNumber = (uint)m_sequenceNumber; 
                message.PublishTime    = DateTime.UtcNow;

                // return the available sequence numbers.
                for (int ii = 0; ii <= m_lastSentMessage && ii < m_sentMessages.Count; ii++)
                {
                    availableSequenceNumbers.Add(m_sentMessages[ii].SequenceNumber);
                }

                // TraceState("PUBLISH KEEPALIVE");
                return message;
            }

            // have to drop unsent messages if out of queue space.
            if (messages.Count > m_maxMessageCount)
            {
                Utils.Trace(
                    "WARNING: QUEUE OVERFLOW. Dropping {2} Messages. Increase MaxMessageQueueSize. SubId={0}, MaxMessageQueueSize={1}", 
                    m_id,
                    m_maxMessageCount,
                    messages.Count - (int)m_maxMessageCount);

                messages.RemoveRange(0, messages.Count - (int)m_maxMessageCount);
            }

            // remove old messages if queue is full.
            if (m_sentMessages.Count > m_maxMessageCount - messages.Count)
            {
                lock (m_diagnostics)
                {
                    m_diagnostics.UnacknowledgedMessageCount += (uint)messages.Count;
                }

                if (m_maxMessageCount <= messages.Count)
                {
                    m_sentMessages.Clear();
                }
                else
                {
                    m_sentMessages.RemoveRange(0, messages.Count);
                }
            }

            // save new message
            m_lastSentMessage = m_sentMessages.Count;
            m_sentMessages.AddRange(messages);
            
            // check if there are more notifications to send.
            moreNotifications = m_waitingForPublish = messages.Count > 1;

            // return the available sequence numbers.
            for (int ii = 0; ii <= m_lastSentMessage && ii < m_sentMessages.Count; ii++)
            {
                availableSequenceNumbers.Add(m_sentMessages[ii].SequenceNumber);
            }

            // TraceState("PUBLISH NEW MESSAGE");
            return m_sentMessages[m_lastSentMessage++];
        }
        public async Task <dynamic> SendAsync(NotificationMessage message, CancellationToken cancellationToken = default)
        {
            Check.NotNull(message, nameof(message));
            Check.NotNull(message.Body, nameof(message.Body));
            Check.NotNull(message.To, nameof(message.To));
            Check.NotNull(message.From, nameof(message.From));
            Check.NotNull(message.From.Name, nameof(message.From.Name));
            Check.NotNull(message.From.Address, nameof(message.From.Address));
            Check.NotNull(message.Subject, nameof(message.Subject));

            //Invalid configuration set name<Não Responda>: only alphanumeric ASCII characters, '_', and '-' are allowed.
            var mailRequest = new SendEmailRequest()
            {
                Destination = new Destination(),
                Source      = $"{message.From.Name} <{message.From.Address}>",
                Message     = new Message()
            };

            mailRequest.Message.Subject = new Content()
            {
                Charset = message.Subject.Charset.GetValueOrDefault(DefaultCharset),
                Data    = message.Subject.Content
            };


            mailRequest.Message.Body = new Body();
            if (message.Body.IsHtml)
            {
                mailRequest.Message.Body.Html = new Content()
                {
                    Charset = message.Body.Charset.GetValueOrDefault(DefaultCharset),
                    Data    = message.Body.Content
                };
            }
            else
            {
                mailRequest.Message.Body.Text = new Content()
                {
                    Charset = message.Body.Charset.GetValueOrDefault(DefaultCharset),
                    Data    = message.Body.Content
                };
            }

            mailRequest.Destination.ToAddresses = message.To.Select(a => $"{a.Name} <{a.Address}>").ToList();

            if (message.BccTo != null)
            {
                mailRequest.Destination.BccAddresses = message.BccTo.Select(a => $"{a.Name} <{a.Address}>").ToList();
            }

            if (message.CcTo != null)
            {
                mailRequest.Destination.CcAddresses = message.CcTo.Select(a => $"{a.Name} <{a.Address}>").ToList();
            }

            if (message.ReplyToAddresses != null)
            {
                mailRequest.ReplyToAddresses = message.ReplyToAddresses.Select(a => $"{a.Name} <{a.Address}>").ToList();
            }

            var policy = CreateDefaultRetryAsyncPolicy();

            var response = await policy.ExecuteAsync(async() => await SimpleEmailClient.SendEmailAsync(mailRequest, cancellationToken));

            return(response);
        }
Example #42
0
        protected void SendNotificationMessage(string message)
        {
            var messageObj = new NotificationMessage(this, message);

            Messenger.Default.Send(messageObj);
        }
        /// <summary>
        /// This method is invoked from NotificationBridge for each new incoming UDP 
        /// Since there will be a new instance for each incoming request 
        /// thread-safety is not necessary.
        /// </summary>
        /// <param name="state"></param>
        public override void DataReceived(Object state)
        {
            NotificationDispatcher NotificationDispatcher = NotificationBridge.Dispatcher;

            NameValueCollection header = new NameValueCollection();

            SerializationReader reader = new SerializationReader((Byte[])state);
            String line = "";
            do
            {
                try
                {
                    line = (String)reader.ReadObject();
                    if (line == Environment.NewLine)
                        break;

                    Int32 ColonPos = line.IndexOf(':');
                    //String[] split = line.Split(new char[] { ':' });
                    //if (split.Length != 2)
                    if (ColonPos < 0)
                        throw new NotificationException_InvalidMulticastHeader("Invalid Header entry: " + line);

                    //header.Add(split[0].ToLower(), split[1].Trim());
                    header.Add(line.Substring(0, ColonPos).ToLower(), line.Substring(ColonPos + 1).Trim());

                    // Is sender the same Dispatcher? Than the message is already handled!
                    if (header["dispatcher"] != null && header["dispatcher"].Contains(NotificationDispatcher.Uuid))
                        return;
                }
                catch (NotificationException_InvalidMulticastHeader imh)
                {
                    throw imh;
                }
                catch (Exception e)
                {
                    throw new NotificationException_InvalidMulticastHeader("Header must ends with newline!", e);
                }

            } while (line != Environment.NewLine);

            if (header["notificationtype"] == null)
                throw new NotificationException_InvalidMulticastHeader("Header must contain a NotificationType!");

            if (header["dispatcher"] == null)
                throw new NotificationException_InvalidMulticastHeader("Header must contain the Dispatcher who sent this message!");

            if (header["senderid"] == null)
                throw new NotificationException_InvalidMulticastHeader("Header must contain the SenderID!");

            // The Dispatcher should only recieve notifications from the restricted VFS (if RestrictedSenderID was defined)
            if (NotificationDispatcher.RestrictedSenderID != String.Empty && NotificationDispatcher.RestrictedSenderID != header["senderid"])
                return;

            ANotificationType notificationType = NotificationBridge.Dispatcher.GetEmptyNotificationTypeFromFullBaseName(header["notificationtype"]);
            NotificationMessage message = new NotificationMessage((Byte[])reader.ReadObject(), notificationType.GetEmptyArgumentInstance());
            message.SenderInfo = new SenderInfo();
            message.SenderInfo.Host = header["host"];
            message.SenderInfo.DispatcherGuid = header["dispatcher"];
            message.SenderInfo.SenderID = header["senderid"];

            NotificationDispatcher.SendNotification(message, false);
        }
        /// <summary>
        /// Invokes the Republish service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="subscriptionId">The subscription id.</param>
        /// <param name="retransmitSequenceNumber">The sequence number of a specific NotificationMessage to be republished.</param>
        /// <param name="notificationMessage">The requested NotificationMessage.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader Republish(
            RequestHeader           requestHeader,
            uint                    subscriptionId,
            uint                    retransmitSequenceNumber,
            out NotificationMessage notificationMessage)
        {
            OperationContext context = ValidateRequest(requestHeader, RequestType.Republish);

            try
            {
                notificationMessage = ServerInternal.SubscriptionManager.Republish(
                    context,
                    subscriptionId,
                    retransmitSequenceNumber);    

                return CreateResponse(requestHeader, context.StringTable);  
            }
            catch (ServiceResultException e)
            {
                lock (ServerInternal.DiagnosticsLock)
                {
                    ServerInternal.ServerDiagnostics.RejectedRequestsCount++;

                    if (IsSecurityError(e.StatusCode))
                    {
                        ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++;
                    }
                }

                throw TranslateException(context, e);
            }  
            finally
            {
                OnRequestComplete(context);
            }   
        }
Example #45
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 internal NotificationEventArgs(
     Subscription          subscription,
     NotificationMessage   notificationMessage,
     IList<string>         stringTable)
 {
     m_subscription        = subscription;
     m_notificationMessage = notificationMessage;
     m_stringTable         = stringTable;
 }
 internal unsafe ConnectEventArgs(AMDeviceNotificationCallbackInfo cbi)
 {
     this.message = cbi.msg;
     this.device = cbi.dev;
 }
Example #47
0
        /// <summary>
        /// Updates the controls displaying the status of the subscription.
        /// </summary>
        private void UpdateStatus()
        {
            NotificationMessage message = null;

            if (m_subscription != null)
            {
                message = m_subscription.LastNotification;
            }

            PublishingEnabledTB.Text = String.Empty;

            if (m_subscription != null)
            {
                PublishingEnabledTB.Text = (m_subscription.CurrentPublishingEnabled)?"Enabled":"Disabled";
            }

            LastUpdateTimeTB.Text = String.Empty;

            if (message != null)
            {
                LastUpdateTimeTB.Text = String.Format("{0:HH:mm:ss}", message.PublishTime.ToLocalTime());
            }

            LastMessageIdTB.Text = String.Empty;

            if (message != null)
            {
                LastMessageIdTB.Text = String.Format("{0}", message.SequenceNumber);
            }

            // determine what window to show.
            bool hasEvents      = false;
            bool hasDatachanges = false;

            foreach (MonitoredItem monitoredItem in m_subscription.MonitoredItems)
            {
                if (monitoredItem.Filter is EventFilter)
                {
                    hasEvents = true;
                }

                if (monitoredItem.NodeClass == NodeClass.Variable)
                {
                    hasDatachanges = true;
                }
            }

            // enable appropriate windows.
            WindowEventsMI.Enabled      = hasEvents;
            WindowDataChangesMI.Enabled = hasDatachanges;

            // show the datachange window if there are no event items.
            if (hasDatachanges && !hasEvents)
            {
                WindowMI_Click(WindowDataChangesMI, null);
            }

            // show events window if there are no datachange items.
            if (hasEvents && !hasDatachanges)
            {
                WindowMI_Click(WindowEventsMI, null);
            }
        }
Example #48
0
 private void NavigateToTab(NotificationMessage <short> notification)
 {
     CurrentPage = Children[notification.Content];
 }
        /// <summary>
        /// Invokes the Publish service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="subscriptionAcknowledgements">The list of acknowledgements for one or more Subscriptions.</param>
        /// <param name="subscriptionId">The subscription identifier.</param>
        /// <param name="availableSequenceNumbers">The available sequence numbers.</param>
        /// <param name="moreNotifications">If set to <c>true</c> the number of Notifications that were ready to be sent could not be sent in a single response.</param>
        /// <param name="notificationMessage">The NotificationMessage that contains the list of Notifications.</param>
        /// <param name="results">The list of results for the acknowledgements.</param>
        /// <param name="diagnosticInfos">The diagnostic information for the results.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object 
        /// </returns>
        public override ResponseHeader Publish(
            RequestHeader                         requestHeader, 
            SubscriptionAcknowledgementCollection subscriptionAcknowledgements, 
            out uint                              subscriptionId, 
            out UInt32Collection                  availableSequenceNumbers, 
            out bool                              moreNotifications, 
            out NotificationMessage               notificationMessage, 
            out StatusCodeCollection              results, 
            out DiagnosticInfoCollection          diagnosticInfos)
        {
            OperationContext context = ValidateRequest(requestHeader, RequestType.Publish);

            try
            {
                /*
                // check if there is an odd delay.
                if (DateTime.UtcNow > requestHeader.Timestamp.AddMilliseconds(100))
                {
                    Utils.Trace(
                        "WARNING. Unexpected delay receiving Publish request. Time={0:hh:mm:ss.fff}, ReceiveTime={1:hh:mm:ss.fff}",
                        DateTime.UtcNow,
                        requestHeader.Timestamp);
                }
                */
                
                Utils.Trace("PUBLISH #{0} RECIEVED. TIME={1:hh:hh:ss.fff}", requestHeader.RequestHandle, requestHeader.Timestamp);
                
                notificationMessage = ServerInternal.SubscriptionManager.Publish(
                    context,
                    subscriptionAcknowledgements,
                    null,
                    out subscriptionId,
                    out availableSequenceNumbers,
                    out moreNotifications,
                    out results,
                    out diagnosticInfos);

                /*
                if (notificationMessage != null)
                {
                    Utils.Trace(
                        "PublishResponse: SubId={0} SeqNo={1}, PublishTime={2:mm:ss.fff}, Time={3:mm:ss.fff}",
                        subscriptionId,
                        notificationMessage.SequenceNumber,
                        notificationMessage.PublishTime,
                        DateTime.UtcNow);
                }
                */

                return CreateResponse(requestHeader, context.StringTable);      
            }
            catch (ServiceResultException e)
            {
                lock (ServerInternal.DiagnosticsLock)
                {
                    ServerInternal.ServerDiagnostics.RejectedRequestsCount++;

                    if (IsSecurityError(e.StatusCode))
                    {
                        ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++;
                    }
                }

                throw TranslateException(context, e);
            }  
            finally
            {
                OnRequestComplete(context);
            }
        }
Example #50
0
 /// <summary>
 /// Queue the notification.
 /// Don't just send it directly.
 /// </summary>
 /// <param name="message"></param>
 protected void Notify(NotificationMessage message)
 {
     _queue.Enqueue(message);
 }
Example #51
0
		unsafe internal ConnectEventArgs(AMDeviceNotificationCallbackInfo cbi) {
			message = cbi.msg;
			device = cbi.dev;
		}
 public void should_return_the_message_icon_for_a_message_message()
 {
     sut = new NotificationMessage(_objectBase, MessageOrigin.Formula, _buildingBlock, NotificationType.Info);
     imageShouldBe(ApplicationIcons.Info);
 }
Example #53
0
 public virtual bool HasMessage(string fieldName, string message)
 {
     var expected = new NotificationMessage(fieldName, message);
     return messages.Exists(actual => actual.Equals(expected));
 }
 private void HandleNotificationMessage(NotificationMessage <NotificationType> message)
 {
     MessageBox.Show(message.Notification, Title, MessageBoxButton.OK, NotificationTypeToImage(message.Content));
 }
        public async Task <IActionResult> Post([FromBody] NotificationMessage content)
        {
            await _customerService.Notify(content?.Message);

            return(CreateResponseOnPost());
        }
        async Task ShowNotification(NotificationMessage message)
        {
            NotificationService.Notify(message);

            await InvokeAsync(() => { StateHasChanged(); });
        }
Example #57
0
        /// <summary>
        /// Publishes a timeout status message.
        /// </summary>
        public NotificationMessage PublishTimeout()
        {
            NotificationMessage message = null;

            lock (m_lock)
            {
                m_expired = true;

                message = new NotificationMessage();

                message.SequenceNumber = (uint)m_sequenceNumber;
                message.PublishTime = DateTime.UtcNow;

                Utils.IncrementIdentifier(ref m_sequenceNumber);

                lock (m_diagnostics)
                {
                    m_diagnostics.NextSequenceNumber = (uint)m_sequenceNumber;
                }

                StatusChangeNotification notification = new StatusChangeNotification();
                notification.Status = StatusCodes.BadTimeout;
                message.NotificationData.Add(new ExtensionObject(notification));
            }

            return message;
        }
Example #58
0
 private void RenameCheckedElementsNotification(NotificationMessage <Mp3Tag> notificationMessage)
 {
     this.IterateCheckedMp3SongsAndDoAction(mp3SongViewModel => mp3SongViewModel.Rename(notificationMessage.Content));
 }
Example #59
0
        /// <summary>
        /// Construct a message from the queues.
        /// </summary>
        private NotificationMessage ConstructMessage(
            Queue<EventFieldList> events,
            Queue<MonitoredItemNotification> datachanges,
            Queue<DiagnosticInfo> datachangeDiagnostics,
            out int notificationCount)
        {
            notificationCount = 0;

            NotificationMessage message = new NotificationMessage();

            message.SequenceNumber = (uint)m_sequenceNumber; 
            message.PublishTime    = DateTime.UtcNow;

            Utils.IncrementIdentifier(ref m_sequenceNumber);

            lock (m_diagnostics)
            {
                m_diagnostics.NextSequenceNumber = (uint)m_sequenceNumber;
            }
             
            // add events.
            if (events.Count > 0 && notificationCount < m_maxNotificationsPerPublish)
            {
                EventNotificationList notification = new EventNotificationList();

                while (events.Count > 0 && notificationCount < m_maxNotificationsPerPublish)
                {
                    notification.Events.Add(events.Dequeue());
                    notificationCount++;
                }

                message.NotificationData.Add(new ExtensionObject(notification));
            }

            // add datachanges (space permitting).
            if (datachanges.Count > 0 && notificationCount < m_maxNotificationsPerPublish)
            {
                bool diagnosticsExist = false;
                DataChangeNotification notification = new DataChangeNotification();

                notification.MonitoredItems  = new MonitoredItemNotificationCollection(datachanges.Count);
                notification.DiagnosticInfos = new DiagnosticInfoCollection(datachanges.Count);

                while (datachanges.Count > 0 && notificationCount < m_maxNotificationsPerPublish)
                {
                    MonitoredItemNotification datachange = datachanges.Dequeue();
                    notification.MonitoredItems.Add(datachange);

                    DiagnosticInfo diagnosticInfo = datachangeDiagnostics.Dequeue();

                    if (diagnosticInfo != null)
                    {
                        diagnosticsExist = true;
                    }
                    
                    notification.DiagnosticInfos.Add(diagnosticInfo);

                    notificationCount++;
                }

                // clear diagnostics if not used.
                if (!diagnosticsExist)
                {
                    notification.DiagnosticInfos.Clear();
                }

                message.NotificationData.Add(new ExtensionObject(notification));
            }

            return message;
        }
Example #60
0
        /// <summary>
        /// Checks if the subscription is ready to publish and returns a notification message.
        /// </summary>
        public NotificationMessage Publish()
        {
            lock (m_lock)
            {
                long currentTime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;

                // check of it is time for a publish.
                if (m_lastPublishTime + m_publishingInterval < currentTime)
                {
                    ListOfMonitoredItemNotification notifications   = new ListOfMonitoredItemNotification();
                    ListOfDiagnosticInfo            diagnosticInfos = new ListOfDiagnosticInfo();

                    // check each monitored item for data changes to send.
                    foreach (MonitoredItem monitoredItem in m_monitoredItems.Values)
                    {
                        while (monitoredItem.Values.Count > 0)
                        {
                            MonitoredItemNotification notification = new MonitoredItemNotification();

                            notification.ClientHandle = monitoredItem.Parameters.ClientHandle;
                            notification.Value        = monitoredItem.Values.Dequeue();

                            notifications.Add(notification);
                            diagnosticInfos.Add(monitoredItem.DiagnosticInfos.Dequeue());
                        }
                    }

                    // check if any notifications were found.
                    if (notifications.Count > 0)
                    {
                        // subscriptions can produce different types of notifications so the notification parameter
                        // is an extensible parameter. This means the object must be manually serialized and wrapped in
                        // an ExtensionObject which specifies the type of data contained in the Body. The complete
                        // UA SDK takes care this housekeeping and will serialize extensible parameters automatically.

                        DataChangeNotification body = new DataChangeNotification();

                        body.MonitoredItems  = notifications;
                        body.DiagnosticInfos = diagnosticInfos;

                        ExtensionObject extension = new ExtensionObject(
                            new ExpandedNodeId(Objects.DataChangeNotification_Encoding_DefaultXml),
                            body);

                        // construct the message and assign a new sequence number.
                        NotificationMessage message = new NotificationMessage();

                        message.SequenceNumber   = ++m_nextSequenceNumber;
                        message.PublishTime      = DateTime.UtcNow;
                        message.NotificationData = new ListOfExtensionObject();

                        message.NotificationData.Add(extension);

                        m_lastPublishTime   = currentTime;
                        m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount);

                        return(message);
                    }
                }

                // check if it is time for a keep alive.
                if (m_nextKeepAliveTime < currentTime)
                {
                    NotificationMessage message = new NotificationMessage();

                    message.SequenceNumber   = m_nextSequenceNumber;
                    message.PublishTime      = DateTime.UtcNow;
                    message.NotificationData = new ListOfExtensionObject();

                    m_nextKeepAliveTime = (long)(currentTime + m_publishingInterval * m_keepAliveCount);

                    return(message);
                }

                return(null);
            }
        }