Skip to content

Commit b10941e

Browse files
committed
logging improvements
1 parent 2584904 commit b10941e

6 files changed

Lines changed: 157 additions & 79 deletions

File tree

Class Library/ActiveUp.Net.Common/Events.cs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -559,15 +559,15 @@ public string Response
559559
#if !PocketPC
560560
[System.Serializable]
561561
#endif
562+
public class AuthEventArgsBase : System.EventArgs
563+
{
564+
public string Message { get; set; }
565+
}
562566

563-
564-
public class AuthenticatedEventArgsBase : System.EventArgs
567+
public class AuthenticatedEventArgsBase : AuthEventArgsBase
565568
{
569+
566570
protected string _username, _password, _host, _serverResponse;
567-
/// <summary>
568-
/// The username used to authenticate the user.
569-
/// </summary>
570-
571571
public string Username
572572
{
573573
get
@@ -601,7 +601,7 @@ public string ServerResponse
601601

602602
public class AuthenticatedEventArgs : AuthenticatedEventArgsBase
603603
{
604-
604+
605605
/// <summary>
606606
/// Constructor.
607607
/// </summary>
@@ -655,6 +655,8 @@ public AuthenticatedOAuth2EventArgs(string username, string host, string server
655655
_username = username;
656656
_host = host;
657657
_serverResponse = serverResponse;
658+
659+
Message = $"AUTHENTICATED: username = {_username}; host = {_host}; serverResponse = {_serverResponse}";
658660
}
659661
/// <summary>
660662
/// Constructor.
@@ -666,6 +668,7 @@ public AuthenticatedOAuth2EventArgs(string username, string serverResponse)
666668
_username = username;
667669
_host = "unknown";
668670
_serverResponse = serverResponse;
671+
Message = $"AUTHENTICATED: username = {_username}; serverResponse = {_serverResponse}";
669672
}
670673

671674
}
@@ -677,8 +680,10 @@ public AuthenticatedOAuth2EventArgs(string username, string serverResponse)
677680
#endif
678681

679682

680-
public class AuthenticatingEventArgsBase : System.EventArgs
683+
684+
public class AuthenticatingEventArgsBase : AuthEventArgsBase
681685
{
686+
682687
protected string _username, _host;
683688

684689
/// <summary>
@@ -702,8 +707,7 @@ public string Host
702707
return _host;
703708
}
704709
}
705-
706-
}
710+
}
707711

708712
public class AuthenticatingEventArgs : AuthenticatingEventArgsBase
709713
{
@@ -757,6 +761,7 @@ public AuthenticatingOAuth2EventArgs(string username, string host)
757761
{
758762
_username = username;
759763
_host = host;
764+
Message = $"AUTHENTICATING: username = {username}; host = {_host}";
760765
}
761766

762767
/// <summary>
@@ -768,6 +773,7 @@ public AuthenticatingOAuth2EventArgs(string username)
768773
{
769774
_username = username;
770775
_host = "unkwown";
776+
Message = $"AUTHENTICATING: username = {username}";
771777
}
772778
}
773779

Class Library/ActiveUp.Net.Common/Logger.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public static class Logger
5858
/// <summary>
5959
/// Specify whether if the logger needs to append the Trace Console.
6060
/// </summary>
61-
public static bool UseTraceConsole { get; set; } = false;
61+
public static bool UseTraceConsole { get; set; } = true;
6262

6363
/// <summary>
6464
/// Specify whether if the logging functions are disabled.

Class Library/ActiveUp.Net.Imap4/Imap4Client.cs

Lines changed: 72 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -918,76 +918,92 @@ internal async Task<string> GetOAuth2Token(string tenantId, string clientId, str
918918
string baseAddress = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
919919
string grant_type = "client_credentials";
920920

921-
bool useMSAL = true;
922-
923-
if (useMSAL)
924-
{
925-
var app = ConfidentialClientApplicationBuilder
926-
.Create(clientId)
927-
.WithTenantId(tenantId)
928-
.WithClientSecret(clientSecret)
929-
.Build();
930-
931-
string[] scopes = new string[] {
932-
"https://outlook.office365.com/.default",
933-
};
934-
935-
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
936-
string accessToken = result.AccessToken;
937-
return accessToken;
938-
}
939-
else
921+
try
940922
{
941-
//[dt] token generation is OK but AUTH fails, further investigations needed
942-
var client = new HttpClient();
923+
bool useMSAL = true;
943924

944-
List<string> scopes = new List<string>
925+
if (useMSAL)
945926
{
946-
"https://outlook.office365.com/.default",
947-
};
948-
949-
var form = new Dictionary<string, string>
927+
var app = ConfidentialClientApplicationBuilder
928+
.Create(clientId)
929+
.WithTenantId(tenantId)
930+
.WithClientSecret(clientSecret)
931+
.Build();
932+
933+
string[] scopes = new string[] {
934+
"https://outlook.office365.com/.default",
935+
};
936+
937+
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
938+
string accessToken = result.AccessToken;
939+
return accessToken;
940+
}
941+
else
950942
{
951-
{"grant_type", grant_type},
952-
{"client_id", clientId},
953-
{"client_secret", clientSecret},
954-
{"scope", string.Join(" ",scopes) }
955-
};
956-
957-
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
958-
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
959-
OAuth2Token token = JsonConvert.DeserializeObject<OAuth2Token>(jsonContent);
960-
return token.AccessToken;
943+
//[dt] token generation is OK but AUTH fails, further investigations needed
944+
var client = new HttpClient();
945+
946+
List<string> scopes = new List<string>
947+
{
948+
"https://outlook.office365.com/.default",
949+
};
950+
951+
var form = new Dictionary<string, string>
952+
{
953+
{"grant_type", grant_type},
954+
{"client_id", clientId},
955+
{"client_secret", clientSecret},
956+
{"scope", string.Join(" ",scopes) }
957+
};
958+
959+
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
960+
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
961+
OAuth2Token token = JsonConvert.DeserializeObject<OAuth2Token>(jsonContent);
962+
return token.AccessToken;
963+
}
964+
}
965+
catch (Exception ex)
966+
{
967+
OnAuthenticating(new AuthenticatingEventArgsBase { Message = $"error during token generation: {ex.Message}\n{ex.StackTrace}" });
968+
throw ex;
961969
}
962970
}
963971

964-
public async Task<string> LoginOAuth2(string userName, string tenantId, string clientId, string clientSecret)
972+
public async Task<bool> LoginOAuth2(string userName, string tenantId, string clientId, string clientSecret)
965973
{
966-
var token = await GetOAuth2Token(tenantId, clientId, clientSecret);
967-
968-
OnAuthenticating(new AuthenticatingOAuth2EventArgs(userName, host));
969-
970-
//https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
971974
string response = "";
972-
string xOauth2;
973-
using (var ms = new MemoryStream(token.Length + 200))
975+
try
974976
{
975-
using (var bw = new BinaryWriter(ms))
977+
var token = await GetOAuth2Token(tenantId, clientId, clientSecret);
978+
979+
OnAuthenticating(new AuthenticatingOAuth2EventArgs(userName, host));
980+
//https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
981+
string xOauth2;
982+
using (var ms = new MemoryStream(token.Length + 200))
976983
{
977-
bw.Write(Encoding.ASCII.GetBytes("user="));
978-
bw.Write(Encoding.ASCII.GetBytes(userName));
979-
bw.Write((byte)1);
980-
bw.Write(Encoding.ASCII.GetBytes("auth=Bearer "));
981-
bw.Write(Encoding.ASCII.GetBytes(token));
982-
bw.Write((byte)1);
983-
bw.Write((byte)1);
984+
using (var bw = new BinaryWriter(ms))
985+
{
986+
bw.Write(Encoding.ASCII.GetBytes("user="));
987+
bw.Write(Encoding.ASCII.GetBytes(userName));
988+
bw.Write((byte)1);
989+
bw.Write(Encoding.ASCII.GetBytes("auth=Bearer "));
990+
bw.Write(Encoding.ASCII.GetBytes(token));
991+
bw.Write((byte)1);
992+
bw.Write((byte)1);
993+
}
994+
xOauth2 = Convert.ToBase64String(ms.ToArray());
984995
}
985-
xOauth2 = Convert.ToBase64String(ms.ToArray());
996+
var cmd = $"AUTHENTICATE XOAUTH2 {xOauth2}";
997+
998+
response = Command(cmd);
999+
}
1000+
catch (Exception ex)
1001+
{
1002+
OnAuthenticating(new AuthenticatingEventArgsBase { Message = $"error during token login: {ex.Message}\n{ex.StackTrace}" });
1003+
return false;
9861004
}
987-
var cmd = $"AUTHENTICATE XOAUTH2 {xOauth2}";
988-
response = Command(cmd);
9891005
OnAuthenticated(new AuthenticatedOAuth2EventArgs(userName, host, response));
990-
return response;
1006+
return true;
9911007
}
9921008

9931009

WindowsFormsApp1/Class1.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,17 @@
77

88
namespace WindowsFormsApp1
99
{
10+
11+
public delegate void AuthenticatingEventHandler(object sender, AuthenticatingEventArgsBase e);
12+
public delegate void AuthenticatedEventHandler(object sender, AuthenticatedEventArgsBase e);
13+
14+
1015
public class MailRepository
1116
{
17+
18+
public event AuthenticatingEventHandler Authenticating;
19+
public event AuthenticatedEventHandler Authenticated;
20+
1221
private Imap4Client _client = null;
1322

1423
public MailRepository(string mailServer, int port, bool ssl)
@@ -19,7 +28,7 @@ public MailRepository(string mailServer, int port, bool ssl)
1928
Client.Connect(mailServer, port);
2029
}
2130

22-
public async Task<string> LoginOAuth2(string user, string tenantId, string clientId, string clientSecret)
31+
public async Task<bool> LoginOAuth2(string user, string tenantId, string clientId, string clientSecret)
2332
{
2433
return await Client.LoginOAuth2(user, tenantId, clientId, clientSecret);
2534
}
@@ -39,11 +48,25 @@ protected Imap4Client Client
3948
get
4049
{
4150
if (_client == null)
51+
{
4252
_client = new Imap4Client();
53+
_client.Authenticating += _client_Authenticating;
54+
_client.Authenticated += _client_Authenticated;
55+
}
4356
return _client;
4457
}
4558
}
4659

60+
private void _client_Authenticated(object sender, AuthenticatedEventArgsBase e)
61+
{
62+
Authenticated?.Invoke(sender, e);
63+
}
64+
65+
private void _client_Authenticating(object sender, AuthenticatingEventArgsBase e)
66+
{
67+
Authenticating?.Invoke(sender, e);
68+
}
69+
4770
private MessageCollection GetMails(string mailBox, string searchPhrase)
4871
{
4972
Mailbox mails = Client.SelectMailbox(mailBox);

WindowsFormsApp1/Form1.Designer.cs

Lines changed: 18 additions & 6 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

WindowsFormsApp1/Form1.cs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,34 @@ private async void simpleButton1_Click(object sender, EventArgs e)
2727
{
2828
MailRepository mailRep = new MailRepository("outlook.office365.com", 993, true);
2929

30-
string tenantId = "APP TENANTID";
31-
string client_id = "APP CLIENTID";
32-
string client_secret = "APP SECRET";
30+
string tenantId = "**********************";
31+
string client_id = "**********************";
32+
string client_secret = "**********************";
3333

34-
await mailRep.LoginOAuth2("[email protected]", tenantId, client_id, client_secret);
35-
mailRep.ActivateMailBox("INBOX");
34+
mailRep.Authenticated += MailRep_Authenticated;
35+
mailRep.Authenticating += MailRep_Authenticating;
3636

37+
bool res = await mailRep.LoginOAuth2("[email protected]", tenantId, client_id, client_secret);
38+
if (res)
39+
{
40+
mailRep.ActivateMailBox("INBOX");
41+
}
42+
}
43+
44+
private void MailRep_Authenticating(object sender, ActiveUp.Net.Mail.AuthenticatingEventArgsBase e)
45+
{
46+
this.Invoke(new Action(() =>
47+
{
48+
memoEdit1.Text += e.Message + Environment.NewLine;
49+
}));
50+
}
51+
52+
private void MailRep_Authenticated(object sender, ActiveUp.Net.Mail.AuthenticatedEventArgsBase e)
53+
{
54+
this.Invoke(new Action(() =>
55+
{
56+
memoEdit1.Text += e.Message + Environment.NewLine; ;
57+
}));
3758
}
3859
}
3960
}

0 commit comments

Comments
 (0)