コード例 #1
0
        public ActionResult <string> Get()
        {
            var graphServiceClient = GetGraphClient();

            var sub = new Microsoft.Graph.Subscription();

            sub.ChangeType         = "updated";
            sub.NotificationUrl    = config.Ngrok + "/api/notifications";
            sub.Resource           = "/users";
            sub.ExpirationDateTime = DateTime.UtcNow.AddMinutes(5);
            sub.ClientState        = "SecretClientState";

            var newSubscription = graphServiceClient
                                  .Subscriptions
                                  .Request()
                                  .AddAsync(sub).Result;

            Subscriptions[newSubscription.Id] = newSubscription;

            if (subscriptionTimer == null)
            {
                subscriptionTimer = new Timer(CheckSubscriptions, null, 5000, 15000);
            }

            return($"Subscribed. Id: {newSubscription.Id}, Expiration: {newSubscription.ExpirationDateTime}");
        }
コード例 #2
0
        public ActionResult <string> Get()
        {
            this.telemetryClient.TrackPageView("Notifications");
            if (graphClient == null)
            {
                graphClient = GraphHelper.Instance.GetGraphClient();
            }

            var sub = new Microsoft.Graph.Subscription();

            sub.ChangeType = "created, updated";
            //sub.NotificationUrl = Configuration["Ngrok"] + "/api/notifications";
            sub.NotificationUrl = Configuration["NotificationsEndpointUri"];
            //sub.Resource = "/users";
            sub.Resource           = Configuration["SubRessource"];
            sub.ExpirationDateTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["ExpirationDateTimeMinutes"]));
            sub.ClientState        = "SecretClientState";
            //Console.WriteLine(sub.NotificationUrl);

            var newSubscription = graphClient
                                  .Subscriptions
                                  .Request()
                                  .AddAsync(sub).Result;

            Subscriptions[newSubscription.Id] = newSubscription;

            if (subscriptionTimer == null)
            {
                subscriptionTimer = new Timer(CheckSubscriptions, null, 5000, 15000);
            }
            var html = $"Subscribed. Id: {newSubscription.Id} Expiration: {newSubscription.ExpirationDateTime}";

            return($"{html}");
        } // Get()
コード例 #3
0
ファイル: MeetingRoomsApi.cs プロジェクト: andrekiba/Gab19
        public async Task <IActionResult> Subscribe(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "subscribe")] HttpRequest req,
            [Table("subscriptions", Connection = "AzureWebJobsStorage")] CloudTable subTable)
        {
            try
            {
                await subTable.CreateIfNotExistsAsync();

                var graphClient = GetGraphClient(configuration.GraphV1);

                var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                var createSub   = JsonConvert.DeserializeObject <CreateSubscription>(requestBody);

                var subscription = new Subscription
                {
                    ChangeType         = createSub.ChangeType,
                    ClientState        = createSub.ClientState,
                    ExpirationDateTime = createSub.ExpirationDateTime,
                    NotificationUrl    = createSub.NotificationUrl.IsNullOrWhiteSpace() ?
                                         $"{configuration.MeetingRoomsApi}/notification" :
                                         createSub.NotificationUrl,
                    Resource = createSub.Resource
                };

                var existingSubs = (await graphClient.Subscriptions.Request()
                                    //.Filter($"resource eq '{subscription.Resource}'")
                                    .GetAsync()).ToList();
                var existingSub = existingSubs.SingleOrDefault(s => s.Resource.Equals(subscription.Resource, StringComparison.InvariantCultureIgnoreCase));
                if (existingSub != null)
                {
                    await graphClient.Subscriptions[existingSub.Id].Request().DeleteAsync();

                    var retrieve = TableOperation.Retrieve <SubscriptionEntity>("SUBSCRIPTION", existingSub.Id);
                    var sub      = (await subTable.ExecuteAsync(retrieve)).Result;
                    if (sub != null)
                    {
                        var deleteOperation = TableOperation.Delete((SubscriptionEntity)sub);
                        await subTable.ExecuteAsync(deleteOperation);
                    }
                }

                var createdSub = await graphClient.Subscriptions.Request().AddAsync(subscription);

                var insertOperation = TableOperation.Insert(createdSub.ToSubscriptionEntity());
                await subTable.ExecuteAsync(insertOperation);

                log.Information($"Created new subscription with id:{createdSub.Id}");

                return(new OkObjectResult(Result.Ok()));
            }
            catch (Exception e)
            {
                var error = $"{e.Message}\n\r{e.StackTrace}";
                log.Error(error);
                return(new OkObjectResult(Result.Fail(error)));
            }
        }
コード例 #4
0
ファイル: Subscription.cs プロジェクト: andrekiba/Gab19
 public static SubscriptionEntity ToSubscriptionEntity(this Microsoft.Graph.Subscription sub)
 {
     return(new SubscriptionEntity
     {
         PartitionKey = "SUBSCRIPTION",
         RowKey = sub.Id,
         Resource = sub.Resource,
         ChangeType = sub.ChangeType,
         ClientState = sub.ClientState,
         NotificationUrl = sub.NotificationUrl,
         ExpirationDateTime = sub.ExpirationDateTime
     });
 }
コード例 #5
0
ファイル: MockGraphHelper.cs プロジェクト: ccwssw/Orca
        public async Task <Subscription> CreateSubscription(int minutes)
        {
            var subscription = new Microsoft.Graph.Subscription()
            {
                NotificationUrl = "http://localhost/",
                Id                        = "7f105c7d-2dc5-4530-97cd-4e7ae6534c07",
                ApplicationId             = "123456789abcdef",
                ChangeType                = "created",
                ClientState               = "xxxxxx",
                ExpirationDateTime        = DateTime.Now.AddMinutes(minutes),
                CreatorId                 = "12345678",
                LatestSupportedTlsVersion = "v1_2",
                LifecycleNotificationUrl  = "https://webhook.azurewebsites.net/api/send/lifecycleNotifications"
            };

            _orcaSubscriptions.Add(subscription);
            return(subscription);
        }
コード例 #6
0
        public async Task <ActionResult <string> > Get()
        {
            var graphServiceClient = GetGraphClient();

            var sub = new Microsoft.Graph.Subscription();

            sub.ChangeType         = "updated";
            sub.NotificationUrl    = config.Ngrok + "/api/notifications";
            sub.Resource           = "/users";
            sub.ExpirationDateTime = DateTime.UtcNow.AddMinutes(15);
            sub.ClientState        = "SecretClientState";

            var newSubscription = await graphServiceClient
                                  .Subscriptions
                                  .Request()
                                  .AddAsync(sub);

            return($"Subscribed. Id: {newSubscription.Id}, Expiration: {newSubscription.ExpirationDateTime}");
        }
コード例 #7
0
        public async Task <ActionResult> Index(string channelId)
        {
            try
            {
                var accessTokenSharePoint = await AadHelper.GetAccessTokenForSharePoint();

                var accessTokenMSGraph = await AadHelper.GetAccessTokenForMicrosoftGraph();

                var sharePointRepository    = new VideoChannelRepository(accessTokenSharePoint);
                var groupsRepository        = new GroupsRepository(graphClient);
                var subscriptionsRepository = new SubscriptionsRepository(graphClient, this.Session, HttpRuntime.Cache);

                var channel = await sharePointRepository.GetChannel(channelId);

                var videos = await sharePointRepository.GetChannelVideos(channelId);

                var groups = await groupsRepository.GetGroups();

                var viewModel = new VideoListViewModel
                {
                    ChannelId    = channelId,
                    ChannelTitle = channel.Title,
                    Videos       = videos,
                    Groups       = groups
                };

                // integration of the webhooks example
                Microsoft.Graph.Subscription result = await subscriptionsRepository.CreateOrReuseSubscription();

                return(View(viewModel));
            }
            catch (Exception ex)
            {
                if (ex is AdalException)
                {
                    // let the ActionFilterAttribute take care of it
                    throw ex;
                }

                return(RedirectToAction("Index", "Error", new { message = ex.Message }));
            }
        }
コード例 #8
0
        // Create a webhook subscription. This action method is called from
        public async Task <Microsoft.Graph.Subscription> CreateOrReuseSubscription()
        {
            var subscriptionId = sessionState[SubscriptionIdKey] as string;

            if (subscriptionId != null)
            {
                return(new Microsoft.Graph.Subscription
                {
                    Id = subscriptionId
                });
            }

            var subscription = new Microsoft.Graph.Subscription
            {
                Resource           = "me/mailFolders('Inbox')/messages",
                ChangeType         = "created",
                NotificationUrl    = ConfigurationManager.AppSettings["ida:NotificationUrl"],
                ClientState        = Guid.NewGuid().ToString(),
                ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 4230, 0)
            };

            var result = await graphClient.Subscriptions.Request().AddAsync(subscription);

            // This app temporarily stores the current subscription ID and client state.
            // These are required so the NotificationController, which is not authenticated, can retrieve an access token keyed from the subscription ID.
            // Production apps typically use some method of persistent storage.

            SubscriptionData data = new Models.SubscriptionData
            {
                ClientState  = result.ClientState,
                userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value
            };

            cache.Insert("subscriptionId_" + result.Id,
                         data, null, DateTime.MaxValue, new TimeSpan(24, 0, 0), System.Web.Caching.CacheItemPriority.NotRemovable, null);

            // Save the latest subscription ID, so we can delete it later.
            sessionState[SubscriptionIdKey] = result.Id;
            return(result);
        }
コード例 #9
0
ファイル: GraphHelper.cs プロジェクト: ccwssw/Orca
        public async Task <Subscription> CreateSubscription(int minutes)
        {
            var sub = new Microsoft.Graph.Subscription();

            sub.ChangeType         = "updated";
            sub.NotificationUrl    = _notificationUrl + "/api/notifications";
            sub.Resource           = "/communications/callRecords";
            sub.ExpirationDateTime = DateTime.UtcNow.AddMinutes(minutes);
            sub.ClientState        = "SecretClientState";

            try
            {
                return(await _graphClient
                       .Subscriptions
                       .Request()
                       .AddAsync(sub));
            }
            catch (ServiceException ex)
            {
                _logger.LogError($"Error creating subscription: {ex.Message}");
                return(null);
            }
        }