Quantcast
Channel: Infragistics Community
Viewing all articles
Browse latest Browse all 2374

App Development using the Office 365 API – Part 2

$
0
0

In one of my previous blog posts, I introduced the Office 365 platform and covered some of the features that the Office 365 API provides for developers. In this blog post, let us explore how to use the Office 365 API from a Windows Store App.

We’ll use the Calendar API as an example and demonstrate in step by step approach on how to add an event from the Windows Store App as well as list all the events from your Office 365 Data.

Let’s see how to use the Calendar API that is available in Office 365.

  1. Check if all the prerequisites are met or installed as per App Development using the Office 365 API – Part 1.
  2. If Visual Studio 2013 is installed, you can install Office Developer Tools for Visual Studio 2013 from here.
  3. Create a new Windows Store (8.1) project in Visual Studio. If you have an existing store project, open it in Visual Studio.

4. You need to install the NuGet package Azure Active Directory Authentication Library to the project. This library provides you with some of the easiest ways to authenticate users with the Microsoft Azure Active Directory. To add this Nuget Package, Right click on the Visual Studio Solution and click “Manage Nuget Package”.

In the Manage NuGet packages Dialog, select online option in the left sidebar and then search for the Azure Active Directory Authentication Library and install it.

5. To use the Calendar API, we need to add the connected services (Office 365) and enable permissions on the Calender for the Windows Store App.

Right click on the project file in Visual Studio and select “Add -> Connected Service”.

In the Service Manager, login to your Office 365 account to register the app and set the permissions for the various API. In this sample, let’s select “Calendar”.

In the Calendar Permissions, select “Read users calendars” and “Have full access to user’s calendars”. And click Apply.

6. Build the Project. This will add the dependent assemblies that are necessary to perform various operations in the Calendar in Office 365 from your Windows Store App.

7. In your Windows Store Project, create a new class with the name “Office365Helper” and add the below data members:

publicstaticreadonlystring DiscoveryResourceId = "https://api.office.com/discovery/";

publicconststring Authority = "https://login.windows.net/common";

publicstaticreadonlyUri DiscoveryServiceEndpointUri = newUri("https://api.office.com/discovery/v1.0/me/");

publicstaticAuthenticationContext _authenticationContext = null;

publicconststring ClientID = "91873825-c6e8-42a9-b6de-40c6f98a851d";

publicstaticUri _returnUri = newUri("http://App4");


Note the ClientID and the return Uri. This would change for each application. You can get these properties by registering your application in the Azure Active Directory.

To register your application in your Microsoft Azure active directory, visit http://azure.microsoft.com/en-us/ and login with your Office 365 credentials.

Navigate to the Active Directory section in your azure account and select the active directory name.

Select the Applications tab and click the “Add” button from the bottom of the screen.

Follow the steps that are shown in the wizard screen where you can register your app.

Once your app is registered, navigate to the “configure” section of your app and copy the ClientID and the return Uri of the app. You need to include it in the respective member of your Office365Helper class.

privatestaticasyncTask<string> GetTokenHelperAsync(AuthenticationContext context, string resourceId)

        {

            string accessToken = null;

            AuthenticationResult result = null;

            result = await context.AcquireTokenAsync(resourceId, ClientID, _returnUri);

            accessToken = result.AccessToken;

            return accessToken;

        }

8. You should authenticate your user with the Azure AD and retrieve the Access Token. Add the below method to your Office365Helper class.

The above method uses the Azure Active Directory Authentication Library to get the access token.

9. The next step is to use the DiscoveryClient to find the service end points. Once the service end points are found, the capability needs to be identified. This can be a Mail capability or Calendar capability, but in this example, it is the Calendar capability. The parameter called capability is used with in the below method so that the same can be used either for the mail or Calendar. Add the below method to the Office365Helper class.

publicstaticasyncTask<OutlookServicesClient> GetOutlookServicesClient(string Capability)

        {

            _authenticationContext = newAuthenticationContext(Authority);

 

            DiscoveryClient discoveryClient = newDiscoveryClient(

            async () => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));

            CapabilityDiscoveryResult result = await discoveryClient.DiscoverCapabilityAsync(Capability);

            var outlookClient = newOutlookServicesClient(

                result.ServiceEndpointUri,

                async () => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));

            return outlookClient;

        }

10. The GetOutlookServicesClient method return the OutlookServicesClient object which can be used to get the list of events or add an event to the Office365.

11. Now, let’s build the UI to list and add the Office 365 functionality within your app. Add the below XAML code snippet under the Page element.

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="637*" />

            <ColumnDefinition Width="729*" />

        Grid.ColumnDefinitions>

        <Grid.RowDefinitions>

            <RowDefinition Height="41*" />

            <RowDefinition Height="343*" />

        Grid.RowDefinitions>

        <TextBlock Grid.Row="0" Text="Calender App" Style="{StaticResource HeaderTextBlockStyle}" Grid.ColumnSpan="2" >TextBlock>

        <Button Name="btnLogin" Grid.Column="1" Content="Login" Width="150" HorizontalAlignment="Right" Click="btnLogin_Click">Button>

        <Grid Grid.Row="1" Grid.ColumnSpan="2">

            <Grid.ColumnDefinitions>

                <ColumnDefinition Width="637*" />

                <ColumnDefinition Width="729*" />

            Grid.ColumnDefinitions>

            <StackPanel>

                <TextBlock Text="Attendee Email" Style="{StaticResource SubheaderTextBlockStyle}" Margin="5,5,5,5">TextBlock>

                <TextBox Name="txtEmail">TextBox>

                <TextBlock Text="Subject" Style="{StaticResource SubheaderTextBlockStyle}" Margin="5,5,5,5">TextBlock>

                <TextBox Name="txtSubject">TextBox>

                <TextBlock Text="Location" Style="{StaticResource SubheaderTextBlockStyle}" Margin="5,5,5,5">TextBlock>

                <TextBox Name="txtLocation">TextBox>

                <TextBlock Text="Content" Style="{StaticResource SubheaderTextBlockStyle}" Margin="5,5,5,5">TextBlock>

                <TextBox Name="txtContent" Height="122" >TextBox>

 

                <Button Name="btnAdd" Click="btnAdd_Click" Width="200">Add DadaButton>

            StackPanel>

            <ListBox Name="LstEvents" Grid.Column="1" Margin="28,25,27,30">ListBox>

        Grid>

Grid>

12. In the code behind, add the data member of type OutlookServicesClient for the page.

privateOutlookServicesClient _outlookClient;

 13. Add the below code snippet to the code behind.

privateasyncvoid btnAdd_Click(object sender, RoutedEventArgs e)

        {

            if (_outlookClient != null)

            {

                // Initialize the attendees

                Attendee[] attendees =

                {

                        newAttendee

                        {

                            EmailAddress = newEmailAddress

                            {

                                Address = "test@developerpublish.com"

                            },

                        },

                };

                // Create an instance of the Event

                Event newEvent = newEvent

                {

                    Subject = txtSubject.Text,

                    Location = newLocation { DisplayName = txtLocation.Text },

                    Attendees = attendees,

                    Start = newDateTimeOffset(newDateTime(2015, 04, 1, 9, 30, 0)),

                    End = newDateTimeOffset(newDateTime(2015, 04, 1, 10, 0, 0)),

                    Body = newItemBody { Content = txtContent.Text }

                };

                // Add the event to the default calendar

                await _outlookClient.Me.Events.AddEventAsync(newEvent);

            }

            LoadCalenderData();

        }

 

        privateasyncvoid LoadCalenderData()

        {

            if (_outlookClient != null)

            {

                // Get the events and display it in the list box.

                var events = await _outlookClient.Me.Events

                            .Take(10)

                            .ExecuteAsync();

                LstEvents.Items.Clear();

                foreach (var calendarEvent in events.CurrentPage)

                {

                    LstEvents.Items.Add(calendarEvent.Subject);

                }

            }

        }

 

        privateasyncvoid btnLogin_Click(object sender, RoutedEventArgs e)

        {

            _outlookClient = awaitOffice365Helper.GetOutlookServicesClient("Calendar");

            LoadCalenderData();

        }

14. Examining the above code snippet, we can get the list of events from Office 365, as shown below.

_outlookClient = awaitOffice365Helper.GetOutlookServicesClient("Calendar");

var events = await _outlookClient.Me.Events

                            .Take(10)

                     .ExecuteAsync();

15. Similarly, to add a new event to Office 365, we can use the Events.AddEventAsync method by passing the Event object.

Event newEvent = newEvent

                {

                    Subject = “DeveloperPublish.com event”,

                    Location = newLocation { DisplayName = “Infragistics Office” },

                    Attendees = ,

                    Start = newDateTimeOffset(newDateTime(2015, 04, 1, 9, 30, 0)),

                    End = newDateTimeOffset(newDateTime(2015, 04, 1, 10, 0, 0)),

                    Body = newItemBody { Content = “ This is a Infragistics log” }

                };

       // Add the event to the default calendar

await _outlookClient.Me.Events.AddEventAsync(newEvent);

16. Run the App. Click the login method to authenticate with your Office 365 credentials. Immediately, you should see the list of events from your Office 365 data as well as the provision to add the new event.

And there you have it!


Viewing all articles
Browse latest Browse all 2374

Trending Articles