private void ApproveApplication(Classes.WorkflowApplicationResponse ApplicationInfo) { try { this.textBox1.Text = string.Format("{0}\r\n{1}\r\n{2}", "Approval Message", ApplicationInfo.application, this.textBox1.Text); string _user = ApplicationInfo.user.Replace("//", @"\"); this.textBox1.Text = string.Format("{0}\r\n{1}\r\n{2}", "Querying SF for app", ApplicationInfo.application, this.textBox1.Text); var _applicationSubscription = _store.GetSubscriptionInfo(_user, ApplicationInfo.application); if (_applicationSubscription != null) { this.textBox1.Text = string.Format("{0}\r\n{1}\r\n{2}", "Subscription is not null", ApplicationInfo.application, this.textBox1.Text); this.textBox1.Text = string.Format("{0}\r\n{1}\r\n{2}", "Found app", ApplicationInfo.application, this.textBox1.Text); this.textBox1.Text = string.Format("{0}\r\n{1}\r\n{2}", "Updating app status", ApplicationInfo.application, this.textBox1.Text); _applicationSubscription.Status = SubscriptionStatus.subscribed; this.textBox1.Text = string.Format("{0}\r\n{1}\r\n{2}", "Saving status", ApplicationInfo.application, this.textBox1.Text); _store.SetSubscriptionInfo(_applicationSubscription); _store.SaveChanges(); } } catch (Exception e) { this.textBox1.Text = string.Format("{0}\r\n{1}", "Error", e.Message); } }
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. SubscriptionStore subscription = SubscriptionStore.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)); } }
public 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 { 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. SubscriptionStore subscription = SubscriptionStore.GetSubscriptionInfo(current.SubscriptionId); // This sample only works with subscriptions that are still cached. if (subscription != null) { if (current.ClientState == subscription.ClientState) { //Store the notifications in application state. A production //application would likely queue for additional processing. var notificationArray = (ConcurrentBag <Notification>)HttpContext.Application["notifications"]; if (notificationArray == null) { notificationArray = new ConcurrentBag <Notification>(); } notificationArray.Add(current); HttpContext.Application["notifications"] = notificationArray; } } } } } } catch (Exception) { // TODO: Handle the exception. // Still return a 202 so the service doesn't resend the notification. } return(new HttpStatusCodeResult(202)); } }
/// <summary> /// Get the changed message details /// Update the local json file /// Continue to update the UI using SignalR /// </summary> /// <param name="notifications"></param> /// <returns></returns> public async Task GetChangedMessagesAsync(IEnumerable <NotificationItem> notifications) { DataService dataService = new DataService(); MailService mailService = new MailService(); int newMessages = 0; foreach (var notification in notifications) { var subscription = SubscriptionStore.GetSubscriptionInfo(notification.SubscriptionId); var graphClient = GraphServiceClientProvider.GetAuthenticatedClient(subscription.UserId); try { // Get the message var message = await mailService.GetMessage(graphClient, notification.ResourceData.Id); // update the local json file if (message != null) { var messageItem = new MessageItem { BodyPreview = message.BodyPreview, ChangeKey = message.ChangeKey, ConversationId = message.ConversationId, CreatedDateTime = (DateTimeOffset)message.CreatedDateTime, Id = message.Id, IsRead = (bool)message.IsRead, Subject = message.Subject }; var messageItems = new List <MessageItem> { messageItem }; dataService.StoreMessage(messageItems, message.ParentFolderId, null); newMessages += 1; } } catch (Exception e) { // ignored } } if (newMessages > 0) { NotificationService notificationService = new NotificationService(); notificationService.SendNotificationToClient(); } }
// 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>(); string serviceRootUrl = "https://graph.microsoft.com/v1.0/"; foreach (var notification in notifications) { SubscriptionStore subscription = SubscriptionStore.GetSubscriptionInfo(notification.SubscriptionId); string accessToken; try { // Get the access token for the subscribed user. accessToken = await AuthHelper.GetAccessTokenForSubscriptionAsync(subscription.UserId, subscription.TenantId); } catch (Exception e) { throw e; } HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serviceRootUrl + notification.Resource); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // Send the 'GET' request. HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(continueOnCapturedContext: false); // Get the messages from the JSON response. if (response.IsSuccessStatusCode) { string stringResult = await response.Content.ReadAsStringAsync(); string type = notification.ResourceData.ODataType; if (type == "#Microsoft.Graph.Message") { Message message = JsonConvert.DeserializeObject <Message>(stringResult); MessageViewModel messageViewModel = new MessageViewModel(message, subscription.UserId); messages.Add(messageViewModel); } } } if (messages.Count > 0) { NotificationService notificationService = new NotificationService(); notificationService.SendNotificationToClient(messages); } }
async void LoadDataFromStore() { IsLoading = true; var products = await SubscriptionStore.GetSubscriptionInfo(); if (products != null) { foreach (var item in products) { if (item.ProductId == SubscriptionStore.MonthlySubscriptionID) { // monthly data MonthlyFeeText = item.LocalizedPrice + "/" + AppResources.month; } if (item.ProductId == SubscriptionStore.AnnuallySubscriptionID) { AnnualFeeText = item.LocalizedPrice + "/" + AppResources.year; } } } var purchasedGoods = await SubscriptionStore.CheckAndUpdateSubscriptionStatus(); if (purchasedGoods != null) { IsSubscribed = true; if (purchasedGoods.Item2.ProductId == SubscriptionStore.MonthlySubscriptionID) { SubscribedTenure = AppResources.monthly; SubscribedDate = AppResources.subscriptionstarted + " " + purchasedGoods?.Item2.TransactionDateUtc.Date.ToString("D"); SubscribedPrice = MonthlyFeeText; } else if (purchasedGoods.Item2.ProductId == SubscriptionStore.AnnuallySubscriptionID) { SubscribedTenure = AppResources.annualy; SubscribedDate = AppResources.subscriptionstarted + " " + purchasedGoods?.Item2.TransactionDateUtc.Date.ToString("D"); SubscribedPrice = AnnualFeeText; } } IsLoading = false; }