Office365 API access for all network users' calendars using c# - outlook

So my main objective is to update network user's outlook calendar from sql server data using office365 api every few minutes. I am stuck at how to get access for other user's outlook calendar? Looked at below link but didnt asnwser much...do i need azure subscription in order to do this? If someone can point me to right direction, that would be great
https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

I am stuck at how to get access for other user's outlook calendar?
In this case, you can consider using the application permission.
In Azure AD:
register a Web Application in your Azure AD.
add “Read and write calendars in all mail boxes” permission
generate the application secret key
In your application, call Office 365 Graph API - create events by using application token.
http://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/user_post_events
var tmgr = new ApplicationTokenManagement();
var token = tmgr.AcquireToken(Settings.ResourceUrlOfGraph);
var api = new Graph.GraphCalendarAPI(token);
JObject body = new JObject
{
{"subject", "Create from Office 365 API"},
{"start", new JObject { { "DateTime", "2016-03-09T00:00:00"}, { "TimeZone", "China Standard Time" } } },
{"end", new JObject { { "DateTime", "2016-03-10T00:00:00"}, { "TimeZone", "China Standard Time" } } },
{"isAllDay", true }
};
var task = api.CreateEventAsync(body, "user#youcompany.com");
task.Wait();
You can find the complete sample here.

Related

Teams bot, transfer a call to another application / voicemail

In our Teams calling bot, we would like to transfer certain calls to specific Teams users, PSTN, but also to an other Teams calling bot and/or voicemail.
For specific Teams users and PSTN we got it working. If we want to transfer a call to another application, we can do so by using its pstn number. But ideally we would also like to transfer using its objectId.
I tried using a transferrequest like this:
var requestBody = new CallTransferRequestBody()
{
TransferTarget = new InvitationParticipantInfo()
{
Identity = new IdentitySet()
{
AdditionalData = new Dictionary<string, object>()
}
}
};
requestBody.TransferTarget.Identity.Application = new Identity { Id = transferTargetId };
//this line does not make any difference
requestBody.TransferTarget.Identity.Application.SetTenantId(tenantId);
But this results in a "Request authorization tenant mismatch." error. Is it possible to directly transfer to another application?
I haven't tried voicemail boxes yet, but if any info on how to transfer to those, is appreciated.
Basically we can transfer an active peer-to-peer call. This is only supported if both the transferee and transfer target are Microsoft Teams users that belong to the same tenant.
However for redirecting call to call queue or auto attendants, you can use the "applicationInstance" identity. The bot is expected to redirect the call before the call times out. The current timeout value is 15 seconds.
const requestBody = {
"targets": [{
"#odata.type": "#microsoft.graph.invitationParticipantInfo",
"identity": {
"#odata.type": "#microsoft.graph.identitySet",
"applicationInstance": {
"#odata.type": "#microsoft.graph.identity",
"displayName": "Call Queue",
"id": queueId
}
}
}],}
Please refer to the documentation here: https://learn.microsoft.com/en-us/graph/api/call-redirect?view=graph-rest-beta&tabs=csharp#request
The redirect API is still having that limitation from my understanding.
But that should work with the new Transfer API:
https://learn.microsoft.com/en-us/graph/api/call-transfer?view=graph-rest-beta&tabs=http

Application Permission support for Dynamics Customer Engagement Web API

We are planning to move from Organization Service to Common Data Service Web API so we could utilize OAuth 2.0 authentication instead of a service account which customer has some security concerns.
Once we did some prototype, we discovered that the Web API authentication is a little different from typical Graph API authentication. It only supports Delegated Permission. Thus a user credential must be presented for acquiring the access token.
Here is the Azure AD Graph API permission for CRM Web API:
Here is the code in acquiring the access token for the sample code at Web API Global Discovery Service Sample (C#)
string GlobalDiscoUrl = "https://globaldisco.crm.dynamics.com/";
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com", false);
UserCredential cred = new UserCredential(username, password);
AuthenticationResult authResult = authContext.AcquireToken(GlobalDiscoUrl, clientId, cred);
Here is another similar post Connect to Dynamics 365 Customer Engagement web services using OAuth although it is more than one year old.
Do you know when MS would support Application permission to completely eliminate the user from authentication? Or there is any particular reason to keep the user here. Thanks for any insights.
[Update 1]
With below answer from James, I did the modification for the code, here is my code
string clientId = "3f4b24d8-61b4-47df-8efc-1232a72c8817";
string secret = "xxxxx";
ClientCredential cred = new ClientCredential(clientId, secret);
string GlobalDiscoUrl = "https://globaldisco.crm.dynamics.com/";
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common", false);
AuthenticationResult authResult = authContext.AcquireToken(GlobalDiscoUrl, cred);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
client.Timeout = new TimeSpan(0, 2, 0);
client.BaseAddress = new Uri(GlobalDiscoUrl);
HttpResponseMessage response = client.GetAsync("api/discovery/v1.0/Instances", HttpCompletionOption.ResponseHeadersRead).Result;
if (response.IsSuccessStatusCode)
{
//Get the response content and parse it.
string result = response.Content.ReadAsStringAsync().Result;
JObject body = JObject.Parse(result);
JArray values = (JArray)body.GetValue("value");
if (!values.HasValues)
{
return new List<Instance>();
}
return JsonConvert.DeserializeObject<List<Instance>>(values.ToString());
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
so I am able to acquire the access token, but it still could not access the global discovery services.
Here is what the access token looks like:
{
"aud": "https://globaldisco.crm.dynamics.com/",
"iss": "https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/",
"iat": 1565802457,
"nbf": 1565802457,
"exp": 1565806357,
"aio": "42FgYEj59uDNtwvxTLnprU0NYt49AA==",
"appid": "3f4b24d8-61b4-47df-8efc-1232a72c8817",
"appidacr": "1",
"idp": "https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/",
"tid": "f8cdef31-a31e-4b4a-93e4-5f571e91255a",
"uti": "w8uwKBSPM0y7tdsfXtAgAA",
"ver": "1.0"
}
By the way, we did already create the application user inside CRM by following the instruction.
Anything I am missing here?
[Update 2]
For WhoAmI request, there are different results. If I am using latest MSAL and with authority "https://login.microsoftonline.com/AzureADDirectoryID/oauth2/authorize", I would be able to get the correct result. If I am using MSAL with "https://login.microsoftonline.com/common/oauth2/authorize", it won't work, I would get unauthorized error. If I am using ADAL 2.29, it is not working for both authority. Here is the working code:
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create("3f4b24d8-61b4-47df-8efc-1232a72cxxxx")
.WithClientSecret("xxxxxx")
// .WithAuthority("https://login.microsoftonline.com/common/oauth2/authorize", false)
.WithAuthority("https://login.microsoftonline.com/3a984a19-7f55-4ea3-a422-2d8771067f87/oauth2/authorize", false)
.Build();
var authResult = app.AcquireTokenForClient(new String[] { "https://crmxxxxx.crm5.dynamics.com/.default" }).ExecuteAsync().Result;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
client.Timeout = new TimeSpan(0, 2, 0);
client.BaseAddress = new Uri("https://crm525842.api.crm5.dynamics.com/");
HttpResponseMessage response = client.GetAsync("api/data/v9.1/WhoAmI()", HttpCompletionOption.ResponseHeadersRead).Result;
if (response.IsSuccessStatusCode)
{
//Get the response content.
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
else
{
throw new Exception(response.ReasonPhrase);
}
The documentation isn't the easiest to follow, but from what I understand you should start with Use OAuth with Common Data Service.
You then have two subtle options when registering your app. The second does not require the Access Dynamics 365/Common Data Service as organization users permission
Giving access to Common Data Service
If your app will be a client which allows the authenticated user to
perform operations, you must configure the application to have the
Access Dynamics 365 as organization users delegated permission.
Or
If your app will use Server-to-Server (S2S) authentication, this step
is not required. That configuration requires a specific system user
and the operations will be performed by that user account rather than
any user that must be authenticated.
This is elaborated further.
Connect as an app
Some apps you will create are not intended to be run interactively by
a user. ... In these cases you can create a special application user
which is bound to an Azure Active Directory registered application and
use either a key secret configured for the app or upload a X.509
certificate. Another benefit of this approach is that it doesn't
consume a paid license.
Register your app
When registering an app you follow many of the same steps ... with the
following exceptions:
You do not need to grant the Access Dynamics 365 as organization users permission.
You will still have a system user record in Dynamics to represent the application registration. This supports a range of basic Dynamics behaviours and allows you to apply Dynamics security to you app.
As opposed to a username and password you can then use the secret to connect.
string serviceUrl = "https://yourorg.crm.dynamics.com";
string clientId = "<your app id>";
string secret = "<your app secret>";
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common", false);
ClientCredential credential = new ClientCredential(clientId, secret);
AuthenticationResult result = authContext.AcquireToken(serviceUrl, credential);
string accessToken = result.AccessToken;
Or a certificate.
string CertThumbPrintId = "DC6C689022C905EA5F812B51F1574ED10F256FF6";
string AppID = "545ce4df-95a6-4115-ac2f-e8e5546e79af";
string InstanceUri = "https://yourorg.crm.dynamics.com";
string ConnectionStr = $#"AuthType=Certificate;
SkipDiscovery=true;url={InstanceUri};
thumbprint={CertThumbPrintId};
ClientId={AppID};
RequireNewInstance=true";
using (CrmServiceClient svc = new CrmServiceClient(ConnectionStr))
{
if (svc.IsReady)
{
...
}
}
You may also want to check out Build web applications using Server-to-Server (S2S) authentication which appears to be a similar (but different).
Use server-to-server (S2S) authentication to securely and seamlessly
communicate with Common Data Service with your web applications and
services. S2S authentication is the common way that apps registered on
Microsoft AppSource use to access the Common Data Service data of
their subscribers. ... Rather than user credentials, the application is authenticated based on a service principal identified by an Azure AD Object ID value which is stored in the application user record.
Aside; if you are currently using the Organization Service .NET object, that is being migrated to using the Web API internally.
Microsoft Dynamics CRM 2011 endpoint
The Dynamics 365 SDK assemblies will be updated to use the Web API.
This update will be fully transparent to you and any code written
using the SDK itself will be supported.

Adaptive Cards: Payment Request

I am currently working on a bot project where i am trying to utilize Microsoft adaptive cards to try send a PaymentRequest to the user. I created a dummy paymentrequest object and inserted it into a Hero card like the documentation says.
var methodList = new List<PaymentMethodData>();
var method = new PaymentMethodData()
{Data = new {supportedNetworks = new[] { "visa", "mastercard", "amex", "discover", "diners", "jcb", "unionpay"} }, SupportedMethods = new[] { "https://bobpay.xyz/pay" } };
methodList.Add(method);
var details = new PaymentDetails {};
var test = new PaymentRequest(null, methodList, details);
var heroCard = new HeroCard
{
Title = "Bob",
Subtitle = "The Builder",
Text = "Kunnen wij het maken!",
Images = new List<CardImage>
{
new CardImage
{
Url = "https://m.media-amazon.com/images/M/MV5BNjRlYjgwMWMtNDFmMy00OWQ0LWFhMTMtNWE3MTU4ZjQ3MjgyXkEyXkFqcGdeQXVyNzU1NzE3NTg#._V1_CR0,45,480,270_AL_UX477_CR0,0,477,268_AL_.jpg"
}
},
Buttons = new List<CardAction>
{
new CardAction
{
Title = "Buy",
Type = PaymentRequest.PaymentActionType,
Value = test,
}
}
};
replyMessage.Attachments.Add(heroCard.ToAttachment());
await context.PostAsync(replyMessage);
I took out a bunch of parameters from the PaymentRequest constructor because i was experimenting with trying to get some kind of feedback. With this i get back nothing but this url which crashed the browser when i try to run it.
"content": {
"buttons": [
{
"title": "Buy",
"type": "openUrl",
"value": "payment://{\"methodData\":[{\"supportedMethods\":[\"https://bobpay.xyz/pay\"],\"data\":{}}],\"details\":{}}"
}
],
I can't find any documentation on how to do this properly but it doesnt seem to say it is deprecated on the documention. I am using bot framework v3 if that helps. I feel like even without some parameters in the PaymentRequest it should still give me something when i click the button.
As stated in this documentation: bot-builder-dotnet-request-payment In order to use the Bot Builder Payments library, you must first:
Create and activate a Stripe account if you don't have one already.
Sign in to Seller Center with your Microsoft account.
Within Seller Center, connect your account with Stripe.
Within Seller Center, navigate to the Dashboard and copy the value of
MerchantID.
Update your bot's Web.config file to set MerchantId to the value that
you copied from the Seller Center Dashboard.
At this time, the Bot Framework SDK supports only Stripe payments directly. If you are using some other provider, you will need to add support for it manually.
Also note: as of 2.25.2019, Bot Builder V4 sdk does not have payments support built in. The Bot Builder V3 sdk does: https://github.com/Microsoft/BotBuilder-Samples/tree/v3-sdk-samples/CSharp/sample-payments (Also, the Bot Framework Emulator V4 does not yet support payments: https://github.com/Microsoft/BotFramework-Emulator/issues/1324 The V3 emulator can be downloaded from here: https://github.com/Microsoft/BotFramework-Emulator/releases/tag/v3.5.37 )

Is it possible to programmatic-ally access the list of contacts in outlook using Office Add In

I am building an Add In which is supposed to grab in addition to the list of contacts an account has, the contacts (to, from, cc and bcc) that are used in the current Item (Message).
As per the documentation, the following instruction gave me zero contacts, although I have contacts in the contacts book, and reading a message with a sender email.
var contacts = Office.context.mailbox.item.getEntities().contacts;
I need to grab the list of contacts I manage in my account:
This list is accessible with the open graph APIs, I wonder if it's also accessible locally with the Office object for Office Add-Ins
Office Js does not provide APIs to get the list of contacts in the account.
But you can get an auth token from Outlook using authentication APIs, then use this token to acquire Graph token to interact with Graph APIs and get the list of contacts
Office.context.auth.getAccessTokenAsync(function (result) {
if (result.status === "succeeded") {
// Use this token to call Web API
var ssoToken = result.value;
// Now send this token to your server and acquire a Graph token
// Server can talk to Graph APIs and get contacts to display
} else {
// Handle error
}
});
Create a Node.js Office Add-in that uses single sign-on
It looks you misunderstood the documentation.
A quote:
The following example accesses the contacts entities in the current item's body.
var contacts = Office.context.mailbox.item.getEntities().contacts;
You could get all contacts using the below link:
Microsoft.Office.Interop.Outlook.Items OutlookItems;
Microsoft.Office.Interop.Outlook.Application outlookObj = new Microsoft.Office.Interop.Outlook.Application();
MAPIFolder Folder_Contacts;
Folder_Contacts = (MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
OutlookItems = Folder_Contacts.Items;
MessageBox.Show("Wykryto kontaktów: " + OutlookItems.Count.ToString());
for (int i = 0; i < OutlookItems.Count; i++)
{
Microsoft.Office.Interop.Outlook.ContactItem contact = (Microsoft.Office.Interop.Outlook.ContactItem)OutlookItems[i+1];
sNazwa = contact.FullName;
sFirma = contact.CompanyName;
sAdress = contact.BusinessAddressStreet;
sMiejscowosc = contact.BusinessAddressPostalCode + " " + contact.BusinessAddressCity;
sEmail = contact.Email1Address;
dataGridView1.Rows.Add(sNazwa, sFirma, sAdress, sMiejscowosc, sEmail);
}
For more information, please refer to the below link:
Get Outlook contacts into C# form-based application

Microsoft Graph API and Outlook API in a Single App

I have an app using MSAL connecting to MS Graph and have been able to use the API. There are couple Outlook APIs such as https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations#GetRoomLists, FindRoomLists currently not available in Graph.
I have the need to use both these APIs in a single app? I read a similar question on Stack Overflow and it mentioned, a Token cannot be used for both Graph and Outlook. I did try and it did not work.
Any suggestions? Is my path to quit using Graph and go to Outlook API?
MSAL will look up the cache and return any cached token which match with the requirement. If such access tokens are expired or no suitable access tokens are present, but there is an associated refresh token(need offline_access scope), MSAL will automatically use that to get a new access token and return it transparently.
For example, if you use MSAL to redeem the authorization code into an access token for microsoft graph, in openid connect owin middleware :
AuthorizationCodeReceived = async (context) =>
{
var code = context.Code;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID,
context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
ConfidentialClientApplication cca =
new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache,null);
string[] scopes = { "Mail.Read" };
try
{
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
}
catch (Exception eee)
{
}
},
With scope Mail.Read , you could get an access token for Microsoft Graph, for the purpose of reading the user's mailbox .Now if you want to call outlook mail rest api in a controller/action , you could use scope: https://outlook.office.com/mail.read , MSAL will acquire token for outlook mail rest api using cached refresh token :
// try to get token silently
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri,new ClientCredential(appKey), userTokenCache, null);
if (cca.Users.Count() > 0)
{
string[] scopes = { "https://outlook.office.com/mail.read" };
try
{
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes,cca.Users.First());
}
catch (MsalUiRequiredException)
{
try
{// when failing, manufacture the URL and assign it
string authReqUrl = await WebApp.Utils.OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url);
ViewBag.AuthorizationRequest = authReqUrl;
}
catch (Exception ee)
{
}
}
}
else
{
}
Please refer to code sample : Integrate Microsoft identity and the Microsoft Graph into a web application using OpenID Connect.

Resources