Ejemplo n.º 1
0
        // Get information about the changed messages and send to browser via SignalR.
        // A production application would typically queue a background job for reliability.
        private async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <Message> messages = new List <Message>();

            foreach (var notification in notifications)
            {
                if (notification.ResourceData.ODataType != "#Microsoft.Graph.Message")
                {
                    continue;
                }

                // Get the stored user object ID.
                var    subscriptionParams = (Tuple <string, string>)_memoryCache.Get("subscriptionId_" + notification.SubscriptionId);
                string userObjectId       = subscriptionParams.Item2;

                // Initialize the GraphServiceClient, using the user ID associated with the subscription.
                GraphServiceClient graphClient = _sdkHelper.GetAuthenticatedClient(userObjectId);
                MessageRequest     request     = new MessageRequest(graphClient.BaseUrl + "/" + notification.Resource, graphClient, null);
                try
                {
                    messages.Add(await request.GetAsync());
                }
                catch (Exception)
                {
                    continue;
                }
            }

            if (messages.Count > 0)
            {
                //NotificationService notificationService = new NotificationService();
                //notificationService.SendNotificationToClient(messages);
            }
        }
        // Get information about the changed messages and send to browser via SignalR.
        // A production application would typically queue a background job for reliability.
        private async Task GetChangedMessagesAsync(IEnumerable <ChangeNotification> notifications)
        {
            List <NotificationViewModel> notificationsToDisplay = new List <NotificationViewModel>();

            foreach (var notification in notifications)
            {
                SubscriptionStore subscription = subscriptionStore.GetSubscriptionInfo(notification.SubscriptionId.Value);

                // Set the claims for ObjectIdentifier and TenantId, and
                // use the above claims for the current HttpContext
                if (!string.IsNullOrEmpty(subscription.UserId))
                {
                    HttpContext.User = ClaimsPrincipalFactory.FromTenantIdAndObjectId(subscription.TenantId, subscription.UserId);
                }

                if (notification.Resource.Contains("/message", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Initialize the GraphServiceClient.
                    var graphClient = await GraphServiceClientFactory.GetAuthenticatedGraphClient(appSettings.Value.BaseUrlWithoutVersion, async() =>
                    {
                        return(await tokenAcquisition.GetAccessTokenForAppAsync($"{appSettings.Value.BaseUrlWithoutVersion}/.default"));
                    });

                    var request = new MessageRequest(graphServiceClient.BaseUrl + "/" + notification.Resource, string.IsNullOrEmpty(subscription.UserId) ? graphClient : graphServiceClient, null);
                    try
                    {
                        var responseValue = await request.GetAsync();

                        notificationsToDisplay.Add(new NotificationViewModel(new
                        {
                            From = responseValue?.From?.EmailAddress?.Address,
                            responseValue?.Subject,
                            SentDateTime = responseValue?.SentDateTime.HasValue ?? false ? responseValue?.SentDateTime.Value.ToString() : string.Empty,
                            To           = responseValue?.ToRecipients?.Select(x => x.EmailAddress.Address)?.ToList(),
                        }));
                    }
                    catch (ServiceException se)
                    {
                        string errorMessage = se.Error.Message;
                        string requestId    = se.Error.InnerError?.AdditionalData["request-id"]?.ToString();
                        string requestDate  = se.Error.InnerError?.AdditionalData["date"]?.ToString();

                        logger.LogError($"RetrievingMessages: { errorMessage } Request ID: { requestId } Date: { requestDate }");
                    }
                }
                else
                {
                    notificationsToDisplay.Add(new NotificationViewModel(notification.Resource));
                }
            }

            if (notificationsToDisplay.Count > 0)
            {
                await notificationService.SendNotificationToClient(notificationHub, notificationsToDisplay);
            }
        }
Ejemplo n.º 3
0
        // Get information about the changed messages and send to browser via SignalR.
        // A production application would typically queue a background job for reliability.
        private async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <MessageViewModel> messages = new List <MessageViewModel>();

            foreach (var notification in notifications)
            {
                if (notification.ResourceData.ODataType != "#Microsoft.Graph.Message")
                {
                    continue;
                }

                SubscriptionStore subscription = subscriptionStore.GetSubscriptionInfo(notification.SubscriptionId);

                // Set the claims for ObjectIdentifier and TenantId, and
                // use the above claims for the current HttpContext
                HttpContext.User = ClaimsPrincipalExtension.FromTenantIdAndObjectId(subscription.TenantId, subscription.UserId);

                // Initialize the GraphServiceClient.
                var graphClient = await GraphServiceClientFactory.GetAuthenticatedGraphClient(async() =>
                {
                    string result = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(
                        HttpContext, new[] { Infrastructure.Constants.ScopeMailRead });
                    return(result);
                });

                MessageRequest request = new MessageRequest(graphClient.BaseUrl + "/" + notification.Resource, graphClient, null);
                try
                {
                    messages.Add(new MessageViewModel(await request.GetAsync(), subscription.UserId));
                }
                catch (ServiceException se)
                {
                    string errorMessage = se.Error.Message;
                    string requestId    = se.Error.InnerError.AdditionalData["request-id"].ToString();
                    string requestDate  = se.Error.InnerError.AdditionalData["date"].ToString();

                    logger.LogError($"RetrievingMessages: { errorMessage } Request ID: { requestId } Date: { requestDate }");
                }
            }

            if (messages.Count > 0)
            {
                NotificationService notificationService = new NotificationService();
                await notificationService.SendNotificationToClient(this.notificationHub, messages);
            }
        }
        // Get information about the changed messages and send to browser via SignalR
        // A production application would typically queue a background job for reliability.
        public async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <Message> messages = new List <Message>();

            foreach (var notification in notifications)
            {
                if (notification.ResourceData.ODataType != "#Microsoft.Graph.Message")
                {
                    continue;
                }

                // Get an access token and add it to the client.
                var        subscriptionParams = (Tuple <string, string>)HttpRuntime.Cache.Get("subscriptionId_" + notification.SubscriptionId);
                string     userObjId          = subscriptionParams.Item2;
                AuthHelper authHelper         = new AuthHelper(new RuntimeTokenCache(userObjId));

                string accessToken = await authHelper.GetUserAccessToken("/");

                var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(requestMessage =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                    return(Task.FromResult(0));
                }));

                var request = new MessageRequest(graphClient.BaseUrl + "/" + notification.Resource, graphClient, null);
                try
                {
                    messages.Add(await request.GetAsync());
                }
                catch (Exception)
                {
                    continue;
                }
            }
            if (messages.Count > 0)
            {
                NotificationService notificationService = new NotificationService();
                notificationService.SendNotificationToClient(messages);
            }
        }
        // Get information about the changed messages and send to browser via SignalR.
        // A production application would typically queue a background job for reliability.
        private async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <MessageViewModel> messages = new List <MessageViewModel>();

            foreach (var notification in notifications)
            {
                if (notification.ResourceData.ODataType != "#Microsoft.Graph.Message")
                {
                    continue;
                }

                SubscriptionStore subscription = subscriptionStore.GetSubscriptionInfo(notification.SubscriptionId);

                // Initialize the GraphServiceClient. This sample uses the tenant ID the cache key.
                GraphServiceClient graphClient = sdkHelper.GetAuthenticatedClient(subscription.TenantId);

                MessageRequest request = new MessageRequest(graphClient.BaseUrl + "/" + notification.Resource, graphClient, null);
                try
                {
                    messages.Add(new MessageViewModel(await request.GetAsync(), subscription.UserId));
                }
                catch (ServiceException se)
                {
                    string errorMessage = se.Error.Message;
                    string requestId    = se.Error.InnerError.AdditionalData["request-id"].ToString();
                    string requestDate  = se.Error.InnerError.AdditionalData["date"].ToString();

                    logger.LogError($"RetrievingMessages: { errorMessage } Request ID: { requestId } Date: { requestDate }");
                }
            }

            if (messages.Count > 0)
            {
                NotificationService notificationService = new NotificationService();

                // Clients use the subscribedUserId to filter for messages that belong to the current user.
                notificationService.SendNotificationToClient(connectionManager, messages);
            }
        }
Ejemplo n.º 6
0
        public async Task <JsonResult> GetMessages()
        {
            Subscription subscription = System.Web.HttpContext.Current.Session["WebHookSubscription"] as Subscription;

            if (subscription != null)
            {
                string xmlpath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Notifications.xml";
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(xmlpath);
                    XmlNodeList    items       = doc.SelectNodes("//value");
                    List <XmlNode> removeItems = new List <XmlNode>();

                    List <string>  resourceArray  = new List <string>();
                    List <Message> retMessageList = new List <Message>();

                    foreach (XmlNode item in items)
                    {
                        string resource = string.Empty, clientState = string.Empty;
                        foreach (XmlNode ss in item.ChildNodes)
                        {
                            if (ss.Name.ToLower().Equals("clientstate"))
                            {
                                if (ss.InnerText != subscription.ClientState)
                                {
                                    resource = string.Empty;
                                    break;
                                }
                            }
                            if (ss.Name.ToLower().Equals("resource"))
                            {
                                resource = ss.InnerText;
                            }
                        }
                        removeItems.Add(item);
                        if (resource != string.Empty && resourceArray.IndexOf(resource) == -1)
                        {
                            resourceArray.Add(resource);
                            break;
                        }
                    }
                    if (removeItems.Count > 0)
                    {
                        XmlNode root = doc.DocumentElement;
                        foreach (XmlNode node in removeItems)
                        {
                            root.RemoveChild(node);
                        }
                        doc.Save(xmlpath);
                    }

                    GraphServiceClient graphServiceClient = await AuthenticationHelper.GetGraphServiceAsync(AADAppSettings.GraphResourceUrl);

                    foreach (var resource in resourceArray)
                    {
                        var requst = new MessageRequest(graphServiceClient.BaseUrl + "/" + resource, graphServiceClient, null);
                        retMessageList.Add(await requst.GetAsync());
                    }
                    return(Json(new { status = "ok", notifications = retMessageList }, JsonRequestBehavior.AllowGet));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return(Json(new { status = "ok" }, JsonRequestBehavior.AllowGet));
        }
        public async Task<JsonResult> GetMessages()
        {
            Subscription subscription = System.Web.HttpContext.Current.Session["WebHookSubscription"] as Subscription;
            if (subscription != null)
            {
                string xmlpath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Notifications.xml";
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(xmlpath);
                    XmlNodeList items = doc.SelectNodes("//value");
                    List<XmlNode> removeItems = new List<XmlNode>();

                    List<string> resourceArray = new List<string>();
                    List<Message> retMessageList = new List<Message>();

                    foreach (XmlNode item in items)
                    {
                        string resource = string.Empty, clientState = string.Empty;
                        foreach (XmlNode ss in item.ChildNodes)
                        {
                            if (ss.Name.ToLower().Equals("clientstate"))
                            {
                                if (ss.InnerText != subscription.ClientState)
                                 {
                                    resource = string.Empty;
                                    break;
                                }
                            }
                            if (ss.Name.ToLower().Equals("resource"))
                            {
                                resource = ss.InnerText;
                            }
                        }
                        removeItems.Add(item);
                        if (resource != string.Empty && resourceArray.IndexOf(resource) == -1)
                        {
                            resourceArray.Add(resource);
                            break;
                        }
                    }
                    if (removeItems.Count > 0)
                    {
                        XmlNode root = doc.DocumentElement;
                        foreach (XmlNode node in removeItems)
                        {
                            root.RemoveChild(node);
                        }
                        doc.Save(xmlpath);
                    }

                    GraphServiceClient graphServiceClient = await AuthenticationHelper.GetGraphServiceAsync(AADAppSettings.GraphResourceUrl);
                    foreach (var resource in resourceArray)
                    {
                        var requst = new MessageRequest(graphServiceClient.BaseUrl + "/" + resource, graphServiceClient, null);
                        retMessageList.Add( await requst.GetAsync());
                    }
                    return Json(new { status = "ok", notifications = retMessageList }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return Json(new { status = "ok" }, JsonRequestBehavior.AllowGet);
        }