Programming Office 365 Jump Start 2

In this series, I will talk about how to start programming with Office 365 in shortest investment of time. I assume my audience will be .NET developers who do not have prior knowledge of Office 365.

Prerequisite: Programming Office 365 Jump Start 1

Exchange Online

Microsoft released Exchange Web Services Managed API SDK for programming messaging solutions for Exchange Online. The SDK is a class library that you can reference in your application and use its methods to connect to Exchange Online and consume its services. Version 1.1 is available at http://bit.ly/z1EY06, but version 1.2 is soon to be released of which documentation can be found here: http://bit.ly/yHcqVE. After installing the SDK, an assembly is available at C:Program FilesMicrosoftExchangeWebServices1.1Microsoft.Exchange.WebServices.dll for accessing Email, Calendar, Tasks and Contacts hosted in the cloud.

Authenticating to Exchange Online

Using the SDK, authenticating to Exchange Online with admin username and password is fairly easy:

var exchange = new ExchangeService(ExchangeVersion.Exchange2010_SP1)
{
     Credentials = new System.Net.NetworkCredential()
     {
          UserName = "admin@mycompany.onmicrosoft.com",
          Password = "passw0rd!"
     }
};

exchange.AutodiscoverUrl(primaryUser, url => true);

If the user is already logged on to that domain, username and password are not required. Use exchange.UseDefaultCredentials = true instead.

Querying User Availability

Prior to scheduling an appointment among two or more attendees, it is better to check whether they are free/busy at that time. Otherwise, it may result in conflict with other appointments.

var attendees = new List<AttendeeInfo>
{
    new AttendeeInfo()
    {
        SmtpAddress = "attendee1@mycompany.onmicrosoft.com",
        AttendeeType = MeetingAttendeeType.Organizer
    },

    new AttendeeInfo()
    {
        SmtpAddress = "attendee2@mycompany.onmicrosoft.com",
        AttendeeType = MeetingAttendeeType.Required
    }
};

var results = exchange.GetUserAvailability(attendees,
     new TimeWindow(DateTime.Now, DateTime.Now.AddDays(3)),
     AvailabilityData.FreeBusyAndSuggestions);

The code above returns whole bunch of information on availability and suggestions (responsible flag for this was AvailabilityData.FreeBusyAndSuggestions) according to availability of the attendees for next three days. You can go ahead and explore by yourself various types of properties this method reveals, but let us take a look at how we can get access to the suggestions that it made:

foreach (var time in results.Suggestions.SelectMany(suggestion =>
     suggestion.TimeSuggestions))
{
     Console.WriteLine(time.MeetingTime + "t" + time.Quality);
}

It is also capable of calculating conflicts automatically and return as part of the TimeSuggestion object.

Creating an Appointment

Now that we have learned how to query user’s availability, let us pick up a suggested time and create an appointment:

var appointment = new Appointment(exchange)
{
     Subject = "Discuss Exchange migration",
     Body = "Let us find a migration process that will
              cause least downtime of the service.",
     Start = appointmentTime,
     End = appointmentTime.AddMinutes(30)
};

appointment.RequiredAttendees.Add(
    "attendee2@mycompany.onmicrosoft.com");

appointment.Save(); 

Sending an Email

The quality indicator of a good SDK is that it gives a solid object model and makes it fairly easy to consume services such as sending email while taking care of the underlying complexities associated with communications all by itself:

var email = new EmailMessage(exchange)
{
     Body = "Hello from my cool C# demo.",
     Subject = "Email by code"
};

email.Attachments.AddFileAttachment("c:\mypic.jpg");
email.ToRecipients.Add("user@mycompany.onmicrosoft.com");
email.Send();

Accessing Folders

In this example, we will get access to a folder and delete all its contents including sub-folders:

var folder = Folder.Bind(exchange,
    WellKnownFolderName.DeletedItems);

folder.Empty(DeleteMode.HardDelete, true);

If we wanted to search for folders that contain certain string, instead of well known folders, we can do so as well. First of all we have to decide our search criteria, then call ExchangeService’s FindFolders method, which takes a folder root to search from, search criteria (filter) and maximum how many folders we are interested in getting in return:

var filter = new SearchFilter.ContainsSubstring(
    FolderSchema.DisplayName, "Reports");

var results = exchange.FindFolders(
    WellKnownFolderName.MsgFolderRoot,
    filter, new FolderView(10));

foreach (var folder in results)
{
    Console.WriteLine(folder.DisplayName);
    // If we have three folders contain 'Reports', output:
    // Annual Reports
    // Monthly Reports
    // Report formats
}

Scheduling Out of Office

Let us schedule an Out of Office automatic reply starting from now for five days, which will send message to people at work only (Internal):

var oofSettings = new OofSettings
{
    InternalReply =
        new OofReply("Hi, thank you for your email, but I am
              out of office."),

    Duration = new TimeWindow(DateTime.Now,
                    DateTime.Now.AddDays(5)),
    State = OofState.Scheduled
};

exchange.SetUserOofSettings(
    "admin@mycompany.onmicrosoft.com", oofSettings);

Notification Streaming

Exchange Web Service SDK allows to listen for change notifications whether it’d be new email arrival, Free/Busy status changed, item created/deleted and so on. Let us see how we can listen for new email arrival:

var subscription = exchange.SubscribeToStreamingNotifications(
    new FolderId[] { WellKnownFolderName.Inbox },
    EventType.NewMail);

var connection = new StreamingSubscriptionConnection(exchange, 30);

connection.AddSubscription(subscription);
connection.OnNotificationEvent += (s, a) =>
    {
        foreach (var item in a.Events.Select(
             notification => notification as ItemEvent))
        {
            Console.WriteLine(string.Format(
                 "Type: {0}, ItemId: {1}",
                 item.EventType, item.ItemId.UniqueId));
        }
    };

connection.Open();

Streaming subscription connection does not allow to persist more than 30 minutes. In order to extend the period of listening time, you will have to subscribe to OnDisconnect event which will be fired upon timeout and then you can invoke connection.Open() once again to establish reconnection and keep listening to the subscribed events.
 

Conclusion

There are countless many things that you can do with the object model. I hope this post has enough exercises to get you started with Exchange Online programming.

Programming Office 365 Jump Start 1

In this series, I will talk about how to start programming with Office 365 in shortest investment of time. I assume my audience will be .NET developers who do not have prior knowledge of Office 365.

Programming Office 365 Jump Start 2

Office 365 Overview

Office 365, publicly made available on June 28, 2011, is a cloud hosted Software + Services offering from Microsoft that includes online versions (read: cloud hosted version) of Exchange Online, and Lync Online, SharePoint Online. Office Web Apps and Office Professional Plus are also included as per plan.

Office 365 is a complete business productivity solution which includes platforms such as SharePoint. Microsoft’s yearly revenue from SharePoint alone is nearly $2B, which gives us a glimpse of the magnitude of success SharePoint has managed to achieve in past 10 years. Because SharePoint is a web application platform, IT Pros and Devs around this industry comprise even bigger of an economics than just that. That also begs a question what is your worth as a developer if you have Office 365 or SharePoint skill in your bag? Office365

Microsoft Exchange is one of the most popular Email, Calendar and Contacts hosting choice for the enterprise. On the other hand, Microsoft Lync, which was formerly known as Microsoft Office Communication Server, is the biggest push from Microsoft to establish itself as an automatic choice in the Unified Communication space. Being the cloud citizen Office 365 offers additional addons to fulfill scaling needs as business grows or shrinks.

Office 365 Plans

As we have just mentioned earlier it is one size fits all, there are three plans to choose from:

  • Professional and small businesses
  • Midsize business and enterprises
  • Education

Enterprises enjoy an additional benefit though, which is being able to offer Office 365 to kiosk users. Some of the scenarios they may cover depending on of course how you use it are Timesheet entry, keep track of schedule on Calendar, Inventory, Request workflows and lookup policies.

Before your company or you decide to go for Office 365, which is as low as $6/user/month, you can always signup for a 30-day trial, which we will use throughout this series for our development work, too.

Full details about plans: http://bit.ly/yIly6l 
How you can deploy to private cloud: http://bit.ly/Aal6LR 
Cost estimator: http://tinyurl.com/78gk5r5

As soon as you have signed up for trial and activated, it gives you control over complete feature-set if you would have purchased a paid subscription as well:

Admin

You can administer everything very easily from this control panel, including user, services, subscriptions, licenses management, etc.

Office 365 Infrastructure Layer

It is hosted on Windows Azure, Microsoft’s cloud, administered via Windows Intune. Windows Intune is a cloud based update and security patches management solution via Web Browser, which by the way, we do not have to worry about, because it is done by Microsoft to keep their Azure infrastructure up-to-date. One of the key benefits of going cloud is that the infrastructure is free from maintenance at consumer level. On top of that, Microsoft guaranties financially backed 99.9% uptime of the service. Therefore, it offers ultimate reliability as well as enterprise-grade security. That said, Microsoft collects no data or put up ads, no document scanning for analytics/mining or improve their service, complete data portability and 5 layers of security: Data, Application, Host, Network and Physical.

All are hosted and configured to work right after your signup, so there is no deployment or configuration really is involved. Furthermore, you can access the same services across different form-factors, such as PC/Mac, Mobile: Windows Phone, Blackberry, iPhone, Android and Symbian. So, according to Forrester survey it came up about more than 300% ROI from Office 365.

Software + Services

Office 365 enjoys generic benefits of going cloud associated with it. However, as a developer you need to know how it is treated in the cloud. In the beginning I have mentioned that Office 365 is a cloud hosted Software + Services offering, before we look into that aspect, let us quickly recap some of the conventional hosting models that we are most familiar with.

Traditional

In traditional Client-Server system, there is a stack of servers for clients to connect over network or internet. As business grows, new servers are to be purchased and as business shrinks servers are needed to be offloaded.

Traditional Cloud/Software as-a Service (SaaS) model solves the problem with scaling up, out and down on business demand. Everything’s hosted in a cloud vendor’s datacenter. If it is Windows Azure, Microsoft has megastructures of datacenters across different continents of the world, which confirms nuclear-bomb-proof part of the cloud feature.

PreCloud

As you can see from the diagram, software is replaced with Cloud based SaaS websites which are accessibly via Web Browser, and rest of the client applications use On-premise servers, ie. locally hosted Lync, Exchange and SharePoint servers.

Software + Services offers best of both worlds, minus the need of network connectivity (managed hosting). Sure, you can use SaaS via Web Browser, but additionally, there are programmable API endpoints, which let Client Applications (App that you will write) to connect and consume services. In this case Exchange, Lync, and SharePoint Online.

S S

Your Apps live on the Client machines, enjoy the faster local data access and processing power, while syncing necessary selective data over the wire from/to the Cloud. These are the kind of apps that we will see how we can write in later posts in this series.

PinPoint: Office 365 Marketplace

Once you have built an app, it is time to go global. You can get yourself listed as vendor as well as your apps as products in the Office 365 Marketplace. Head over to http://pinpoint.com or for detailed guide: http://bit.ly/eMVqaf. Potential customers can then discover your apps and purchase from there, or perhaps even better contact your company for further customization or support. PinPoint allows your company to acquire global reach.