Esempio n. 1
0
        static async Task Main(string[] args)
        {
            // Create a GraphServiceClient instance with the defined TokenCredential
            string[] scopes = { "Presence.Read.All" };

            // And a TokenCredential implementation
            var credential = new UsernamePasswordCredential(
                Environment.GetEnvironmentVariable("Username"),
                Environment.GetEnvironmentVariable("Password"),
                Environment.GetEnvironmentVariable("AZURE_TENANT_ID"),
                Environment.GetEnvironmentVariable("AZURE_CLIENT_ID"));

            // Create a GraphServiceClient instance with the defined TokenCredential
            var graphClient = new GraphServiceClient(credential, scopes);

            // Load the X509Certificate and add it to the subscription object
            var certificate = X509CertificateUtility.LoadCertificate(StoreName.My,
                                                                     StoreLocation.CurrentUser,
                                                                     Environment.GetEnvironmentVariable("CertificateThumbprint"));

            if (certificate == null)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed to load certificate!");
                return;
            }

            // Create a subscription
            var subscription = new Subscription
            {
                ChangeType              = "updated",
                IncludeResourceData     = true,
                NotificationUrl         = $"https://piasys-presence-notifications.azurewebsites.net/api/NotifyPresence?code={Environment.GetEnvironmentVariable("NotifyFunctionKey")}",
                Resource                = $"/communications/presences/{Environment.GetEnvironmentVariable("TargetUserIds")}",
                ExpirationDateTime      = DateTime.UtcNow.AddMinutes(2),
                ClientState             = "something",
                EncryptionCertificateId = !string.IsNullOrEmpty(certificate?.FriendlyName) ? certificate.FriendlyName : certificate?.Subject,
            };

            // Associate the X509Certificate to the subscription object
            subscription.AddPublicEncryptionCertificate(certificate);

            try
            {
                Subscription subscriptionResult = await graphClient.Subscriptions.Request().AddAsync(subscription);

                string responseMessage = $"Subscription successfully registered with ID: {subscriptionResult.Id}";
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(responseMessage);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                return;
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> Subscribe(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Subscribe function triggered!");

            // Process the subscription request
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    request     = JsonConvert.DeserializeObject <SubscriptionRequest>(requestBody);

            // Create a GraphServiceClient instance with the defined TokenCredential
            var graphClient = GraphUtility.GetGraphClient();

            // Load the X509Certificate and add it to the subscription object
            var certificate = X509CertificateUtility.LoadCertificate(StoreName.My,
                                                                     StoreLocation.CurrentUser,
                                                                     Environment.GetEnvironmentVariable("CertificateThumbprint"));

            if (certificate == null)
            {
                log.LogError("Failed to load certificate!");
                return(new StatusCodeResult(500));
            }

            // Create a subscription
            var subscription = new Subscription
            {
                ChangeType              = request.ChangeType,
                IncludeResourceData     = true,
                NotificationUrl         = $"{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/api/notify?code={Environment.GetEnvironmentVariable("NotifyFunctionKey")}",
                Resource                = request.Resource,
                ExpirationDateTime      = DateTime.UtcNow.AddMinutes(15),
                ClientState             = request.ClientState,
                EncryptionCertificateId = !string.IsNullOrEmpty(certificate?.FriendlyName) ? certificate.FriendlyName : certificate?.Subject,
            };

            // Associate the X509Certificate to the subscription object
            subscription.AddPublicEncryptionCertificate(certificate);

            try
            {
                Subscription subscriptionResult = await graphClient.Subscriptions.Request().AddAsync(subscription);

                string responseMessage = $"Subscription successfully registered with ID: {subscriptionResult.Id}";
                return(new OkObjectResult(responseMessage));
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
                return(new StatusCodeResult(500));
            }
        }
Esempio n. 3
0
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
                                                        FunctionContext executionContext)
        {
            // Prepare the response object
            HttpResponseData response = null;

            // Get the logger
            var log = executionContext.GetLogger("SubscribeFunction");

            log.LogInformation("Subscribe function triggered!");

            // Process the subscription request
            var request = await JsonSerializer.DeserializeAsync <SubscriptionRequest>(req.Body,
                                                                                      new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true
            });

            // Create a GraphServiceClient instance with the defined TokenCredential
            var graphClient = GraphUtility.GetGraphClient();

            // Load the X509Certificate and add it to the subscription object
            var certificate = X509CertificateUtility.LoadCertificate(StoreName.My,
                                                                     StoreLocation.CurrentUser,
                                                                     Environment.GetEnvironmentVariable("CertificateThumbprint"));

            if (certificate == null)
            {
                var certificateError = "Failed to load certificate!";
                log.LogError(certificateError);

                response = req.CreateResponse(HttpStatusCode.InternalServerError);
                response.WriteString(certificateError);

                return(response);
            }

            // Create a subscription
            var subscription = new Subscription
            {
                ChangeType              = request.ChangeType,
                IncludeResourceData     = true,
                NotificationUrl         = $"https://{Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME")}/api/notify?code={Environment.GetEnvironmentVariable("NotifyFunctionKey")}",
                Resource                = request.Resource,
                ExpirationDateTime      = DateTime.UtcNow.AddMinutes(15),
                ClientState             = request.ClientState,
                EncryptionCertificateId = !string.IsNullOrEmpty(certificate?.FriendlyName) ? certificate.FriendlyName : certificate?.Subject,
            };

            // Associate the X509Certificate to the subscription object
            subscription.AddPublicEncryptionCertificate(certificate);

            try
            {
                Subscription subscriptionResult = await graphClient.Subscriptions.Request().AddAsync(subscription);

                string responseMessage = $"Subscription successfully registered with ID: {subscriptionResult.Id}";
                log.LogInformation(responseMessage);

                response = req.CreateResponse(HttpStatusCode.OK);
                response.WriteString(responseMessage);

                return(response);
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);

                response = req.CreateResponse(HttpStatusCode.InternalServerError);
                response.WriteString(ex.Message);

                return(response);
            }
        }