skip to Main Content

Let’s start by saying that this problem make me crazy 🙂

Backgroung info:
I need to add Graph support to an old project ASP.NET, Framework 4.7.2 and webform.
I know, it’s an old and crap technology, but I need it works.

The code (C#) below works fine in a new project ASP.NET core Web App template

    
using Azure.Identity;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using Microsoft.Graph.Models;


namespace WebApplication_testGraph.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
   
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

            var scopes = new[] { "https://graph.microsoft.com/.default" };

            var tenantId = "xxx";

            // Values from app registration
            var clientId = "xxx";
            var clientSecret = "xxx";

            // using Azure.Identity;
            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
            var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret, options);

            var accessToken =  clientSecretCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes) { });

           // Console.WriteLine(accessToken.Token);

            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

            var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
            {
                Message = new Message
                {
                    Subject = "Meet for lunch?",
                    Body = new ItemBody
                    {
                        ContentType = BodyType.Text,
                        Content = "The new cafeteria is open.",
                    },
                    ToRecipients = new List<Recipient>
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "[email protected]",
                },
            },
        },
                },
                SaveToSentItems = false,
            };

             graphClient.Users["[email protected]"].SendMail.PostAsync(requestBody);
        }

    }
}

But in a project with ASP.NET Framework 4.7.2, C# and Web Form, about the same code do not work.
I have no errors, but nothing really happens

this is the code:


using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Me.SendMail;
using Microsoft.Graph.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


public partial class test_email : System.Web.UI.Page
{
    protected async Task Page_LoadAsync(object sender, EventArgs e)
    {
       
        var scopes = new[] { "https://graph.microsoft.com/.default" };

        var tenantId = "xxx";

        // Values from app registration
        var clientId = "xxxx";
        var clientSecret = "xxxx";

        // using Azure.Identity;
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };

        // https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
        var clientSecretCredential = new ClientSecretCredential(
            tenantId, clientId, clientSecret, options);

        var accessToken = await clientSecretCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes) { });

        //Console.WriteLine(accessToken.Token);

        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

        var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
        {
            Message = new Message
            {
                Subject = "Meet for lunch?",
                Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = "The new cafeteria is open.",
                },
                ToRecipients = new List<Recipient>
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "[email protected]",
                },
            },
        },
            },
            SaveToSentItems = false,
        };

        await graphClient.Users["[email protected]"].SendMail.PostAsync(requestBody);

            }
}

Could you help me to understand why the code do not work in this conditions, please?

TNX

I tryed to change

protected async Task Page_LoadAsync(object sender, EventArgs e)

in

public async Task Page_LoadAsync(object sender, EventArgs e)

2

Answers


  1. Chosen as BEST ANSWER

    On step ahead. Now the code below works and send email in a ASP.NET 4.8, Web Form, Framework 4.7.2. Now I need to add some attach but MessageAttachmentsCollectionPage is inaccessibile due to its protection level

    ublic partial class Test_email : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        { }
    
        public async void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 
                await GetGizmosSvcAsync();
    
                // 
                Response.Redirect("Post.aspx");
            }
            catch (Exception ex)
            {
                
            }
        }
         
        public async Task GetGizmosSvcAsync()
        {
            try
            {
               
              
                var scopes = new[] { "https://graph.microsoft.com/.default" };
                var tenantId = "";
                var clientId = "";
                var clientSecret = "";
               
                var attachments = new MessageAttachmentsCollectionPage();
    
                var options = new TokenCredentialOptions
                {
                    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
                };
    
                var clientSecretCredential = new ClientSecretCredential(
                    tenantId, clientId, clientSecret, options);
    
                var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
    
                var requestBody = new Microsoft.Graph.Users.Item.SendMail.SendMailPostRequestBody
                {
                    Message = new Message
                    {
                        Subject = "Meet for lunch XXXX1?",
                        Body = new ItemBody
                        {
                            ContentType = BodyType.Text,
                            Content = "The new cafeteria is open.",
                        },
                        ToRecipients = new List<Recipient>
                    {
                        new Recipient
                        {
                            EmailAddress = new EmailAddress
                            {
                                Address = "[email protected]",
                            },
                        },
                    },
                    },
                    SaveToSentItems = false,
                };
    
                await graphClient.Users["[email protected]"].SendMail.PostAsync(requestBody);
    
    
            }
            catch (Exception ex)
            {
                
            }
        }
    
    
    }


  2. I have no errors, but nothing really happens -> I created a new .net framework 4.8 MVC project(I didn’t install 4.7 in my machine), then in the HomeController/Index method, I added codes below which worked well.

    using Azure.Identity;
    using Microsoft.Graph;
    
    public async Task<ActionResult> Index()
    {
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var tenantId = "tenantId ";
        var clientId = "clientId ";
        var clientSecret = "clientSecret ";
        var clientSecretCredential = new ClientSecretCredential(
                        tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
        var users = await graphClient.Users.GetAsync();
        return View();
    }
    

    But if the method name is IndexAsync(), I will get 404 error.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search