public void updates_cached_routes()
        {
            var cache = new SubscriptionCache(new ChannelGraph(), new ITransport[] { new InMemoryTransport(), });

            var subscriptions1 = new[]
            {
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription()
            };

            subscriptions1[0].MessageType = typeof(string).FullName;
            subscriptions1[1].MessageType = typeof(int).FullName;

            var subscriptions2 = new[] { ObjectMother.ExistingSubscription() };

            subscriptions2[0].MessageType = typeof(int).FullName;

            cache.LoadSubscriptions(subscriptions1);
            cache.FindDestinationChannels(new Envelope {
                Message = "Foo"
            });
            cache.FindDestinationChannels(new Envelope {
                Message = 42
            });
            cache.CachedRoutes.ContainsKey(typeof(string)).ShouldBeTrue();
            cache.CachedRoutes.ContainsKey(typeof(int)).ShouldBeTrue();

            cache.LoadSubscriptions(subscriptions2);
            cache.CachedRoutes.ContainsKey(typeof(string)).ShouldBeFalse();
            cache.CachedRoutes.ContainsKey(typeof(int)).ShouldBeTrue();
        }
Esempio n. 2
0
        private void RetryPendingSubscriptions(IPEndPoint ep, Type type = null)
        {
            _log.DebugFormat("Retrying to find publishers for pending subscriptions {0}", type == null ? string.Empty : string.Format("of type {0}", type.Name));
            try
            {
                var cache = type == null?SubscriptionCache.ToArray() : SubscriptionCache.Where(c => c.Value == type).ToArray();

                foreach (var sub in cache)
                {
                    if (type != null && sub.Value != type)
                    {
                        return;
                    }

                    Message subscription = new Message(sub.Key)
                    {
                        Type = MessageType.Subscribe,
                        Data = Serializer.Serialize(sub.Value)
                    };

                    _log.DebugFormat("Resending subscription request message {0}", subscription.Id);
                    SenderBase.SendAsync(subscription, ep);
                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Could not retry pending subscriptions: {0}\n{1}", ex.Message, ex.StackTrace);
                return;
            }
        }
        public void can_replace_the_subscriptions()
        {
            var cache = new SubscriptionCache(new ChannelGraph(), new ITransport[] { new InMemoryTransport(), });

            var subscriptions1 = new Subscription[]
            {
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription()
            };

            var subscriptions2 = new Subscription[]
            {
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription(),
                ObjectMother.ExistingSubscription()
            };

            cache.LoadSubscriptions(subscriptions1);

            cache.ActiveSubscriptions.ShouldHaveTheSameElementsAs(subscriptions1);

            cache.LoadSubscriptions(subscriptions2);

            cache.ActiveSubscriptions.ShouldHaveTheSameElementsAs(subscriptions2);
        }
        /// <summary>
        /// Gets the subscriptions.
        /// </summary>
        /// <returns></returns>
        private IEnumerable <string> GetSubscriptions()
        {
            if (this.Subscription != null)
            {
                return(this.Subscription);
            }

            // Use selected subscription (for example, by command "Select-AzSubscription {subscriptionId}")
            if (this.TryGetDefaultContext(out var context))
            {
                var subscriptionId = context.Subscription?.Id;
                if (subscriptionId != null)
                {
                    return(new List <string> {
                        subscriptionId
                    });
                }
            }

            var accountSubscriptions = this.DefaultContext.Account.GetSubscriptions();

            if (accountSubscriptions.Length > 0)
            {
                return(accountSubscriptions);
            }

            return(SubscriptionCache.GetSubscriptions(this.DefaultContext));
        }
        // Get information about the changed messages and send to the browser via SignalR.
        // A production application would typically queue a background job for reliability.
        public async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <MessageViewModel> messages = new List <MessageViewModel>();

            foreach (var notification in notifications)
            {
                SubscriptionDetails subscription = SubscriptionCache.GetSubscriptionCache().GetSubscriptionInfo(notification.SubscriptionId);

                var graphClient = GraphHelper.GetAuthenticatedClient(subscription.UserId, subscription.RedirectUrl);

                // Get the message
                var message = await graphClient.Me.Messages[notification.ResourceData.Id].Request()
                              .Select("id,subject,bodyPreview,createdDateTime,isRead,conversationId,changeKey")
                              .GetAsync();

                // Clear the additional data from Graph (purely for display purposes)
                message.AdditionalData.Clear();

                MessageViewModel messageViewModel = new MessageViewModel(message, subscription.UserId);
                messages.Add(messageViewModel);
            }
            if (messages.Count > 0)
            {
                NotificationService notificationService = new NotificationService();
                notificationService.SendNotificationToClient(messages);
            }
        }
        public async Task <ActionResult> Listen()
        {
            // Validate the new subscription by sending the token back to Microsoft Graph.
            // This response is required for each subscription.
            if (Request.QueryString["validationToken"] != null)
            {
                var token = Request.QueryString["validationToken"];
                return(Content(token, "plain/text"));
            }

            // Parse the received notifications.
            else
            {
                try
                {
                    var notifications = new Dictionary <string, Notification>();
                    using (var inputStream = new System.IO.StreamReader(Request.InputStream))
                    {
                        JObject jsonObject = JObject.Parse(inputStream.ReadToEnd());
                        if (jsonObject != null)
                        {
                            // Notifications are sent in a 'value' array. The array might contain multiple notifications for events that are
                            // registered for the same notification endpoint, and that occur within a short timespan.
                            JArray value = JArray.Parse(jsonObject["value"].ToString());
                            foreach (var notification in value)
                            {
                                Notification current = JsonConvert.DeserializeObject <Notification>(notification.ToString());

                                // Check client state to verify the message is from Microsoft Graph.
                                var subscription = SubscriptionCache.GetSubscriptionCache().GetSubscriptionInfo(current.SubscriptionId);

                                // This sample only works with subscriptions that are still cached.
                                if (subscription != null)
                                {
                                    if (current.ClientState == subscription.ClientState)
                                    {
                                        // Just keep the latest notification for each resource.
                                        // No point pulling data more than once.
                                        notifications[current.Resource] = current;
                                    }
                                }
                            }

                            if (notifications.Count > 0)
                            {
                                // Query for the changed messages.
                                await GetChangedMessagesAsync(notifications.Values);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // TODO: Handle the exception.
                    // Still return a 202 so the service doesn't resend the notification.
                }
                return(new HttpStatusCodeResult(202));
            }
        }
Esempio n. 7
0
        public void SetUp()
        {
            var container = new Container(x => {
                x.For <SubscriptionSettings>().Use(theSettings);
            });

            _runtime = FubuTransport.For <SubscriptionRegistry>().StructureMap(container).Bootstrap();

            theCache = _runtime.Factory.Get <ISubscriptionCache>().As <SubscriptionCache>();
        }
        public void SubscriptionCache_CanBeCreated_IsCreated()
        {
            Mock <IConfigurationRepository> configurationRepository = new Mock <IConfigurationRepository>();

            var config = Options.Create(new ServiceSettings
            {
                CacheTimeout = 30
            });

            ISubscriptionCache <SubscriptionGroup> subscriptionCache = new SubscriptionCache(configurationRepository.Object, config);

            subscriptionCache.ShouldNotBeNull();
        }
Esempio n. 9
0
        public void SetUp()
        {
            var container = new Container(x => {
                x.For <SubscriptionSettings>().Use(theSettings);
            });

            var registry = new SubscriptionRegistry();

            registry.StructureMap(container);

            _runtime = registry.ToRuntime();

            theCache = _runtime.Get <ISubscriptionCache>().As <SubscriptionCache>();
        }
        /// <summary>
        /// Gets the subscriptions.
        /// </summary>
        /// <returns></returns>
        private IEnumerable <string> GetSubscriptions()
        {
            if (this.Subscription != null)
            {
                return(this.Subscription);
            }

            var accountSubscriptions = this.DefaultContext.Account.GetSubscriptions();

            if (accountSubscriptions.Length > 0)
            {
                return(accountSubscriptions);
            }

            return(SubscriptionCache.GetSubscriptions(this.DefaultContext));
        }
        public void GetSendFromCache()
        {
            ExTraceGlobals.MailCallTracer.TraceDebug((long)this.GetHashCode(), "RecipientWellEventHandler.GetSendFromCache");
            RecipientInfoCacheEntry entry = AutoCompleteCacheEntry.ParseLogonExchangePrincipal(base.OwaContext.UserContext.ExchangePrincipal, base.OwaContext.UserContext.SipUri, base.OwaContext.UserContext.MobilePhoneNumber);

            AutoCompleteCacheEntry.RenderEntryJavascript(this.Writer, entry);
            this.Writer.Write(";");
            SubscriptionCache cache = SubscriptionCache.GetCache(base.OwaContext.UserContext);

            cache.RenderToJavascript(this.Writer);
            this.Writer.Write(";");
            SendFromCache sendFromCache = SendFromCache.TryGetCache(base.OwaContext.UserContext);

            if (sendFromCache != null)
            {
                sendFromCache.Sort();
                sendFromCache.RenderToJavascript(this.Writer);
            }
        }
Esempio n. 12
0
        public async Task <ActionResult> DeleteSubscription()
        {
            string baseUrl       = $"{Request.Url.Scheme}://{Request.Url.Authority}";
            var    subscriptions = SubscriptionCache.GetSubscriptionCache().DeleteAllSubscriptions();

            try
            {
                foreach (var subscription in subscriptions)
                {
                    await SubscriptionHelper.DeleteSubscription(subscription.Key, baseUrl);
                }

                return(RedirectToAction("SignOut", "Account"));
            }
            catch (Exception ex)
            {
                ViewBag.Message = BuildErrorMessage(ex);
                return(View("Error", ex));
            }
        }
        public void Write(string eventName, Dictionary <string, string> data)
        {
            Guard.AgainstNullOrEmpty(() => eventName, eventName);

            var subscriptions = SubscriptionCache.GetAll(eventName);
            var results       = new List <SubscriptionDeliveryResult>();

            subscriptions.ForEach(sub =>
            {
                var result = NotifySubscription(sub, eventName, data);
                if (result != null)
                {
                    results.Add(result);
                }
            });

            if (results.Any())
            {
                SubscriptionService.UpdateResults(results);
            }
        }
        public void Write(WebhookEvent webhookEvent)
        {
            Guard.AgainstNull(() => webhookEvent, webhookEvent);

            var subscriptions = SubscriptionCache.GetAll(webhookEvent.EventName);
            var results       = new List <SubscriptionDeliveryResult>();

            subscriptions.ForEach(sub =>
            {
                var result = NotifySubscription(sub, webhookEvent);
                if (result != null)
                {
                    results.Add(result);
                }
            });

            if (results.Any())
            {
                SubscriptionService.UpdateResults(results);
            }
        }
Esempio n. 15
0
        protected bool AddFromRecipient(MessageItem message)
        {
            bool flag  = false;
            bool flag2 = false;
            List <Participant> list          = new List <Participant>();
            RecipientInfo      recipientInfo = (RecipientInfo)base.GetParameter("From");

            if (recipientInfo != null)
            {
                flag |= base.GetExchangeParticipantsFromRecipientInfo(recipientInfo, list);
                if (list.Count == 1)
                {
                    message.From = list[0];
                    SubscriptionCacheEntry subscriptionCacheEntry;
                    if (RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
                    {
                        SubscriptionCache.GetCache(base.UserContext);
                    }, this.GetHashCode()) && base.UserContext.SubscriptionCache.TryGetEntry(message.From, out subscriptionCacheEntry))
                    {
                        flag2 = true;
                        message[MessageItemSchema.SharingInstanceGuid]   = subscriptionCacheEntry.Id;
                        message[ItemSchema.SentRepresentingEmailAddress] = subscriptionCacheEntry.Address;
                        message[ItemSchema.SentRepresentingDisplayName]  = subscriptionCacheEntry.DisplayName;
                    }
                    if (!flag2)
                    {
                        this.fromParticipant = message.From;
                    }
                }
            }
            else
            {
                message.From = null;
            }
            return(flag);
        }
 public void Get()
 {
     ExTraceGlobals.MailCallTracer.TraceDebug((long)this.GetHashCode(), "ClientCacheEventHandler.Get");
     base.ResponseContentType = OwaEventContentType.Javascript;
     this.Writer.WriteLine("{");
     this.Writer.Write("sAcc : \"");
     using (RecipientWellEventHandler recipientWellObject = new RecipientWellEventHandler())
     {
         RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
         {
             using (TextWriter textWriter = new StringWriter(CultureInfo.InvariantCulture))
             {
                 recipientWellObject.GetCache(textWriter, this.OwaContext, this.UserContext);
                 Utilities.JavascriptEncode(textWriter.ToString(), this.Writer);
             }
         }, this.GetHashCode());
     }
     this.Writer.WriteLine("\",");
     this.Writer.Write("sPr : \"");
     RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
     {
         RecipientInfoCacheEntry entry = AutoCompleteCacheEntry.ParseLogonExchangePrincipal(base.UserContext.ExchangePrincipal, base.UserContext.SipUri, base.UserContext.MobilePhoneNumber);
         using (TextWriter textWriter = new StringWriter(CultureInfo.InvariantCulture))
         {
             AutoCompleteCacheEntry.RenderEntryJavascript(textWriter, entry);
             Utilities.JavascriptEncode(textWriter.ToString(), this.Writer);
         }
     }, this.GetHashCode());
     this.Writer.WriteLine("\",");
     RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
     {
         SubscriptionCache cache = SubscriptionCache.GetCache(base.UserContext);
         SendAddressDefaultSetting sendAddressDefaultSetting = new SendAddressDefaultSetting(base.UserContext);
         SubscriptionCacheEntry subscriptionCacheEntry;
         if (cache.TryGetSendAsDefaultEntry(sendAddressDefaultSetting, out subscriptionCacheEntry))
         {
             this.Writer.Write("sDfltFr : \"");
             using (TextWriter textWriter = new StringWriter(CultureInfo.InvariantCulture))
             {
                 subscriptionCacheEntry.RenderToJavascript(textWriter);
                 Utilities.JavascriptEncode(textWriter.ToString(), this.Writer);
             }
             this.Writer.WriteLine("\",");
         }
     }, this.GetHashCode());
     this.Writer.Write("sSc : \"");
     RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
     {
         SubscriptionCache cache = SubscriptionCache.GetCache(base.UserContext);
         using (TextWriter textWriter = new StringWriter(CultureInfo.InvariantCulture))
         {
             cache.RenderToJavascript(textWriter);
             Utilities.JavascriptEncode(textWriter.ToString(), this.Writer);
         }
     }, this.GetHashCode());
     this.Writer.WriteLine("\",");
     this.Writer.Write("sMruc : \"");
     RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
     {
         SendFromCache sendFromCache = SendFromCache.TryGetCache(base.UserContext);
         if (sendFromCache != null)
         {
             using (TextWriter textWriter = new StringWriter())
             {
                 sendFromCache.RenderToJavascript(textWriter);
                 Utilities.JavascriptEncode(textWriter.ToString(), this.Writer);
             }
         }
     }, this.GetHashCode());
     this.Writer.WriteLine("\",");
     this.Writer.Write("sLng : '");
     Utilities.JavascriptEncode(base.UserContext.UserCulture.Name, this.Writer);
     this.Writer.WriteLine("',");
     this.Writer.Write("iThmId : ");
     this.Writer.Write(ThemeManager.GetIdFromStorageId(base.UserContext.UserOptions.ThemeStorageId));
     this.Writer.WriteLine(",");
     this.Writer.Write("sSigHtml : '");
     RenderingUtilities.RenderSignature(this.Writer, base.UserContext, true);
     this.Writer.WriteLine("',");
     this.Writer.Write("sSigTxt : '");
     RenderingUtilities.RenderSignature(this.Writer, base.UserContext, false);
     this.Writer.WriteLine("',");
     this.Writer.Write("fSig : ");
     this.Writer.Write((base.UserContext.IsFeatureEnabled(Feature.Signature) && base.UserContext.UserOptions.AutoAddSignature) ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fSp : '");
     this.Writer.Write(base.UserContext.IsFeatureEnabled(Feature.SpellChecker));
     this.Writer.WriteLine("',");
     this.Writer.Write("iSp : '");
     this.Writer.Write(base.UserContext.UserOptions.SpellingDictionaryLanguage);
     this.Writer.WriteLine("',");
     this.Writer.Write("fSpSn : ");
     this.Writer.Write(base.UserContext.UserOptions.SpellingCheckBeforeSend ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("iFmtBrSt : ");
     this.Writer.Write((int)base.UserContext.UserOptions.FormatBarState);
     this.Writer.WriteLine(",");
     this.Writer.Write("sMruFnts : '");
     Utilities.JavascriptEncode(base.UserContext.UserOptions.MruFonts, this.Writer);
     this.Writer.WriteLine("',");
     this.Writer.Write("sInitFntNm : '");
     Utilities.JavascriptEncode(base.UserContext.UserOptions.ComposeFontName, this.Writer);
     this.Writer.WriteLine("',");
     this.Writer.Write("sInitFntSz : '");
     this.Writer.Write(base.UserContext.UserOptions.ComposeFontSize);
     this.Writer.WriteLine("',");
     this.Writer.Write("sDefFntStyl : '");
     RenderingUtilities.RenderDefaultFontStyle(this.Writer, base.UserContext);
     this.Writer.WriteLine("',");
     this.Writer.Write("fDefFntBold : ");
     this.Writer.Write((int)(base.UserContext.UserOptions.ComposeFontFlags & FontFlags.Bold));
     this.Writer.WriteLine(",");
     this.Writer.Write("fDefFntItalc : ");
     this.Writer.Write((int)(base.UserContext.UserOptions.ComposeFontFlags & FontFlags.Italic));
     this.Writer.WriteLine(",");
     this.Writer.Write("fDefFntUndl : ");
     this.Writer.Write((int)(base.UserContext.UserOptions.ComposeFontFlags & FontFlags.Underline));
     this.Writer.WriteLine(",");
     this.Writer.Write("fTxt : ");
     this.Writer.Write((int)base.UserContext.UserOptions.ComposeMarkup);
     this.Writer.WriteLine(",");
     this.Writer.Write("fShwBcc : ");
     this.Writer.Write(base.UserContext.UserOptions.AlwaysShowBcc ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fShwFrm : ");
     this.Writer.Write(base.UserContext.UserOptions.AlwaysShowFrom ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fAEnc : ");
     this.Writer.Write(OwaRegistryKeys.AlwaysEncrypt ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fASgn : ");
     this.Writer.Write(OwaRegistryKeys.AlwaysSign ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fSgn : ");
     this.Writer.Write(base.UserContext.UserOptions.SmimeSign ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fEnc : ");
     this.Writer.Write(base.UserContext.UserOptions.SmimeEncrypt ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("fMstUpd : ");
     this.Writer.WriteLine(OwaRegistryKeys.ForceSMimeClientUpgrade ? 1 : 0);
     this.Writer.WriteLine(",");
     this.Writer.Write("oMailTipsConfig : {");
     this.Writer.Write("'fHideByDefault' : ");
     this.Writer.Write(base.UserContext.UserOptions.HideMailTipsByDefault ? 1 : 0);
     RecipientCache.RunGetCacheOperationUnderDefaultExceptionHandler(delegate
     {
         CachedOrganizationConfiguration instance = CachedOrganizationConfiguration.GetInstance(base.UserContext.ExchangePrincipal.MailboxInfo.OrganizationId, CachedOrganizationConfiguration.ConfigurationTypes.All);
         this.Writer.Write(",");
         this.Writer.Write("'fEnabled' : ");
         this.Writer.Write(instance.OrganizationConfiguration.Configuration.MailTipsAllTipsEnabled ? 1 : 0);
         this.Writer.Write(",");
         this.Writer.Write("'fMailboxEnabled' : ");
         this.Writer.Write(instance.OrganizationConfiguration.Configuration.MailTipsMailboxSourcedTipsEnabled ? 1 : 0);
         this.Writer.Write(",");
         this.Writer.Write("'fGroupMetricsEnabled' : ");
         this.Writer.Write(instance.OrganizationConfiguration.Configuration.MailTipsGroupMetricsEnabled ? 1 : 0);
         this.Writer.Write(",");
         this.Writer.Write("'fExternalEnabled' : ");
         this.Writer.Write(instance.OrganizationConfiguration.Configuration.MailTipsExternalRecipientsTipsEnabled ? 1 : 0);
         this.Writer.Write(",");
         this.Writer.Write("'iLargeAudienceThreshold' : ");
         this.Writer.Write(instance.OrganizationConfiguration.Configuration.MailTipsLargeAudienceThreshold);
     }, this.GetHashCode());
     this.Writer.Write("}");
     this.Writer.Write("}");
 }