Thursday, September 1, 2016

EWS: Basic references

EWS Managed API

I've been working with EWS over the last few months and I've amassed a list of my favorite resources on this topic. I wanted to share this list with the hope that it would save someone time getting accustomed to the technology. One beginner tip- there is EWS and EWS Managed API. Sample code for the two are often listed next to each other and can be confusing for a new programmer. When you see EWS, think SOAP protocol (XML requests and responses), and when you see EWS Managed API, think C# code. The EWS Managed API is available as a NuGet package (Microsoft.Exchange.WebServices) for Visual Studio or by download link, here. Without further ado, I give you my favorite basic resources.

EWS Managed API, EWS, and web services in Exchange
This is a pretty excellent high-level overview of what EWS is, how you can use it, and pointing you to more information on your area of interest.

EWS Best Practices
This is a list of links as well, but it will be updated by the author, whereas this list is not guaranteed to be. It's a great place to start as a beginning and return to when you have a better grip of what EWS is.

Get started with "Hello World!"
So you want to get a summary paragraph and jump right into creating a project? This is the place to start. Although, as soon as you're done, I recommend circling back to the EWS Best Practices 

EWS Managed API reference
This is for the when you're feeling adventurous and are ready to dive a little deeper into exploring the Microsoft.Exchange.WebServices namespace.

Links of Common EWS Questions
This is also, a list of links, but the common questions are here. Watch out, this is an old reference and some articles might be out of date. Once you have an idea of what your question is, or the answer is, check for an updated reference on the web.

EWS Throttling in Exchange
Eventually you might be dealing with load, and this is a must read for learning about throttling for EWS in Exchange.

EWS: Sending a collection of e-mails using CreateItems

Exchange Web Services (EWS) is an API for getting and sending content to an Exchange server. This post will explain how to send a collection of e-mails with one call to EWS, and identify one if it's shortcomings.

First you will need a list of Item objects. In EWS, the Item class is a generic item. Classes such as Appointment, Contact, ContactGroup, EmailMessage, PostItem, and Task all inherit from the Item class. As such, the CreateItems() method can create any object that inherits from the Item class. This example, will demonstrate using EmailMessage objects to create real e-mails.

List<Item> items = new List<Item>();
EmailMessage email_1 = new EmailMessage(_service)
    ToRecipients = { new EmailAddress("") },
    Subject = "Hello",
    Body = "Hello World!"
EmailMessage email_2 = new EmailMessage(_service)
    ToRecipients = { new EmailAddress("") },
    Subject = "Hello 2",
    Body = "Hello World!"


Then, pass the list of Items to the CreateItems() method.

ServiceResponseCollection<ServiceResponse> responseCollection = _service.CreateItems(items, inboxFolder.Id, MessageDisposition.SendOnly, null);

That's it. 

There are limitations on the number of items you will be allowed to send at once due to Exchange server policies on throttling, etc. Next, consider adding an attachment to these e-mails..


Then, if we try to create these e-mails with attachments using the CreateItems call again, this time it will not work. This is because, "under the hood, the workflow for sending emails with attachments is: CreateItem, CreateAttachment, and then SendItem. CreateItems is a batch of CreateItem calls, it doesn't contain the workflow to break out items with attachments" (referencing StackOverflow post)

So, the way to send e-mails with attachments using EWS is one at a time, and the way to send a group of emails without attachments is using CreateItems.


EWS: Throttling policies on bulk operations

Exchange Web Services (EWS) Managed API is a fantastic API that lets you do a whole lot of interesting things from C# code that allows the program to interact with Exchange. EWS has bulk operations, such as CreateItems, that let's a program send up a bundle of items from C# code to be created by the Exchange server.

The downside to this is that the Exchange server has quite a few throttling policies that it imposes on groups or individual accounts. This has the effect of squandering efforts to perform large bulk operations when it exceeds a particular throttling policy. This is because the Exchange throttling policies are like a cop pulling over speeding drivers, they don't let one driver run everyone off the road, rather a connection has to stay within the limits defined by the throttling policies. A grand overview of EWS throttling policies in Exchange 2013 server are outlined here.

This blog post attempts to outline what Exchange 2013 throttling policies might be run into using EWS to perform bulk Mail operation for creating mail items (i.e., just the CreateItems call  to create emails and not dealing with Calendar, Contact, or Meeting items) and how to appropriately change them. Reading up on EWS best practices is highly encouraged so that ramping down throttling policies is not used as an improvement for faulty code. Then, when its decided that its still necessary to fiddle with the throttling polices, definitely read up on the best practices for EWS throttling. The most important point to remember might be that Exchange throttling policies effect not only EWS, but also client connection to the server for other programs like Outlook and ActiveSync. If you're not sure whether Exchange is throttling your program you can check the EWS logs on the Client Access server (CAS) to investigate whether operations are being throttled.

This MSDN article is the most helpful to get started, as it outlines the specific throttling policies that effect EWS in Exchange 2013. The policies below are pulled from that list, with the italicized description from MSDN, followed by an explanation as to why they might come into play using the batch request CreateItems:

  • EwsCutoffBalance
    • MSDN - "Defines the resource consumption limits for EWS user before that user is completely blocked from performing operations on a specific component."
    • The CreateItems call consumes resources on the Client Access server (CAS). When this limit is exceed the server may return errors like "the operation has timed out". From researching EwsCutoffBalance policy further, it seems to be defined by the total number of milliseconds an EWS connection is consuming a specific resource. In other words, if an EWS operation takes longer than the EwsCutoffBalance (in ms), then the operation will time out. 
  • EwsMaxBurst
    • MSDN - "Defines the amount of time that an EWS user can consume an elevated amount of resources before being throttled. This is measured in milliseconds. This value is set separately for each component."
    • This throttling policy is a little bit easier to understand from its name and description. EwsMaxBurst is expressed in milliseconds. This should be less than EwsRechargeRate.
  • EwsRechargeRate
    • MSDN - "Defines the rate at which an EWS user's budget is recharged (budget grows by) during the budget time."
    • This throttling policy is also expressed in milliseconds. When a resource is being throttled by say the EwsMaxBurst or EwsCutoffBalance policy, it will start to recharge at the rate defined by this policy. Presumably, the throttling policy will be "recharged" in the time defined by EwsRechargeRate, but more research and testing needs to be done to be sure.
  • EwsMaxConcurrency
    • MSDN - "
    • Defines the number of concurrent open connections that a specific user can have against an Exchange server that is using EWS at one time. The default value for Exchange 2013 and Exchange Online is 27. 
    • This policy applies to all operations except for streaming notifications.
    • "
    • This policy is worth noting because there may be concurrent connections going on while one is making a call to the CreateItems bulk operation.

The first three policies above are all measured in milliseconds, and should be ordered in this way:
EwsMaxBurst < EwsRechargeRate < EwsCutoffBalance

This has been an intermediate look at what EWS throttling policies should be considered for changing when using the bulk operation CreateItems.


Thursday, July 28, 2016

How to handle SQL command timeouts in .NET code

If you're a .NET programmer you might be familiar with using SqlConnection and SqlCommand objects to perform database queries.

They might look something like this:

You might think the liberal use of 'using' statements disposes of all the resources that might still be lingering around after execution of this method completes. You might think that there are no 'leakages' happening here. This might be true in most cases however this blog post is going to pose a counter-example.

Consider the scenario where just before the process releases the "Exclusive (X) lock" it has on the resource it is INSERTing, the command timeout expires.

Now what happens?

The command timeout expiration event causes SQL execution to stop immediately for this process. The COMMIT command that follows implicitly from the INSERT statement above is never executed. A Senior Escalation Engineer at Microsoft, Bob Dorr, has the following to say about command timeouts:
At the time of the [command timeout] the transaction is not rolled back unless transaction abort (XACT_ABORT) has been enabled.  The client needs to submit a rollback.  If the client does not submit the rollback and continues other processing the transaction remains open and the behavior scope of the application becomes undefined.
What Bob Dorr is saying is that in the above code, MyInsertMethod1, fails to defensively handle the command timeout exception because it does not end the transaction if such an exception occurs. The transaction can be ended by a COMMIT or ROLLBACK. Furthermore, the side effects of this are not good. The transaction still holds onto any locks that it has, or in other words the transaction is still open and it will "leak".

To fix this, we should catch the command timeout exception and explicitly commit or rollback the transaction to close it properly.

"Stale" SQL transactions that are not closed properly can cause poor database performance. They can cause other transactions to block on any locks that they have, thus causing more command timeouts and the problem can snowball.



How it Works: Attention, Attention or Should I say Cancel the Query and Be Sure to Process Your Results - 

CommandTimeout - How to handle it properly? -

CommandTimeout - How to handle it properly? - code example -

How to Minimize SQL Server Blocking -

Wednesday, June 22, 2016

EWS: How to "spoof" an e-mail in your Inbox without sending it

A few weeks ago I was looking for a way to "spoof" an e-mail in my Inbox using EWS. The e-mail would be to and from users other than myself. Without going into too much detail, the reason for this was I wanted to use my Exchange Inbox as a place to store messages for a group of people, even if I wasn't a sender or recipient of the message, and I didn't want the users to receive these e-mails that I was storing.

I was unlucky then, but yesterday when researching another topic I found the answer in this Microsoft article, How to: Import items by using EWS in Exchange! I hope the wording in the blog post grabs people that are looking for the same thing that I was. I never would have found the above mentioned article from how I was searching in the first place.

The trick is setting a specific property on the EmailMessage that makes it not appear as a Draft before Saving it in my Inbox.

EmailMessage email = new EmailMessage(_ewsService);
// Indicate that this email is not a draft. Otherwise, the email
// will appear as a draft to clients.
ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new
     ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
email.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1);
// Set To/From properties to whatever I like
email.From = new EmailAddress("");
email.Body = new MessageBody(BodyType.Text, "Hey, need a hand hiding
     candy this year? -S.C.");

What appears is an e-mail in my inbox from Santa Clause to the Easter Bunny. It looks like a normal e-mail not a Draft that I'm working on. The only odd thing (other than it's an e-mail in my Inbox and I'm not a recipient) is that it doesn't appear as an unread e-mail. It looks like an e-mail that I've already read by default.


Thursday, June 16, 2016

Developing OAuth with Skype Web SDK: admin pre-requisites

This blog post will cover the system-level steps an Office 365 administrator needs to do in order to "turn on" the Skype Web SDK functionality for code being written with OAuth authentication. Some of these steps may sound familiar if you've read the previous post "UCWA 2.0 and Skype for Business online: Create an Azure AD application". What you will need to accomplish this task is the Sign-on URL and Reply URL for the web application that will be using OAuth and Skype Web SDK. If you're unsure of either of these talk with the developer that will be configuring the web application.

Link Azure and Office 365 accounts together

This step is outside the scope of this article, but it is worth noting. This Microsoft reference "Set up your Office 365 and Azure AD tenant" provides more information.

Create an Azure AD application

To start, this step will be a modified version of the directions from Microsoft's page "Registering your application in Azure AD".  Follow the directions from both sections, register your application with Azure AD and configure your app for OAuth implicit grant flow.

After provisioning the application in step 6, be sure to configure the application's Reply URL. This step isn't mentioned in the Microsoft directions. Another modification is at step 9 under registering your application, select as many of the delegated permissions as desired. For example, the permission "Read and manage Skype for Business user contacts and groups" is required to add or edit contacts and groups in the buddy list. At step 10, do not configure your application to be multi-tenant if it doesn't need to be.

After the above steps are completed, some values from the configuration page should be stored for yourself and others. Any developer or application that will be using the Skype Web SDK will need to know the Client ID and have a Key. To generate a Key, select a duration and save the changes. The Key will appear once it is saved.

Tenant admin consent

Microsoft explains this section best, from their reference "Developing Web SDK applications for Skype for Business Online",
The Skype for Business Online permissions are tenant administrator consent only. For an app to be used by all users of an O365 tenant, a tenant administrator must provide consent. To provide consent for all users in the tenant, construct the following URL for your app as shown in the example below.
Note: update the Client ID and Reply URL (redirect URI) for your app.
    &client_id= ...

After the admin grants consent for the tenant, Microsoft will attempt to redirect you to the Reply URL. If you enter the wrong Reply URL, after the admin gives consent a Microsoft error page will appear and in the tiny error message at the bottom it will say, the reply address 'your Reply URL' does not match the reply addresses configured for the application: your Client ID. If the web app is not running at that time, you will see a browser "ERR_CONNECTION_REFUSED" error.


Thursday, May 26, 2016

UCWA 2.0 and Skype for Business online: Authentication without a browser

Authentication without a browser

Many samples that demonstrate authenticating with UCWA 2.0 use the Office 365 log-in page in the web browser. However, it's also possible to write a C# console application that doesn't require opening a web browser for the user to authenticate. This requires create a native Azure AD application. This quote from the Microsoft article Authentication using Azure AD explains the difference:
"As part of registration, you specify whether your app is a Web application, such as an MVC or Web Forms solution, or a native app, such as a smart phone or other mobile device. Azure AD uses this information to generate resources your app will need to authenticate with Azure."
Once the native app is registered in Azure AD then its time to write the code that does the authentication dance with the UCWA and Skype for Business online servers, which goes something like this.

Authenticating with UCWA 2.0

  1. Make an auto-discovery request to the service endpoint to find the user's UCWA home pool
  2. Request an access token from the server location that the auto-discovery request provided
  3. Make an auto-discovery request with the new access token to the UCWA application resource
    1. Possibly make the above request again if a redirect or user resource is returned instead of an application URL. If the application URL isn't returned, replace the UCWA application resource from the above step with either the redirect resource or user resource.
  4. Once the application services root URL is obtained from the previous step, request an access token from that server
  5. With the new access token, send a POST request to the application resource URL to register your console app with the UCWA server.

There's a helpful StackOverflow post about the above flow, found here.

The trick to getting authentication to work with a headless client is that the username and password need to be available to the program to pass to the resource when requesting an access token, such as:

var ar = await authContext.AcquireTokenAsync(resourceUri, UcSettings.ApplicationId, new UserCredential(UcSettings.Username, UcSettings.Password));


Skype Web SDK

The latest developer API for Skype for Business is the Skype Web SDK. The Skype Web SDK provides a whole host of functions to interact with Skype for Business in Office 365. Unlike UCWA 2.0, the SDK feels more complete for Office 365 with abilities such as adding groups. Another difference is it is programmed in JavaScript!

The SDK doesn't need to be installed as it is hosted on a Skype site. All you need to do is add a <script/> tag in the HTML file, as follows:
<script src=""></script>
This is called bootstrapping the JavaScript libraries hosted at the Skype Web SDK entry point which happens to be

Like the Unified Communications Web API (UCWA) 2.0, that has been written about in previous blog posts, the Skype Web SDK authenticates users against Skype for Business on Office 365 servers through Azure Active Directory. The pre-requisite in both these cases is to have an Azure AD app configured to allow API access to the Skype for Business app. More information on how this works with Skype Web SDK can be found here, under "App Registration".

To learn more about what's supported in this developer platform or to inspect the matrix of features offered by the Skype Web SDK, check out this page under "Feature support matrix".


Friday, May 20, 2016

UCWA 2.0 and Skype for Business online: Adding a contact

Authentication and Resources

While authentication using Azure AD and resources in UCWA 2.0 are not the topic of this post, they're necessary to get to the point of adding a contact to the Skype for Business contact list. I found this StackOverflow post very helpful, along with the Microsoft documentation. Also, understanding the nested formation of URL resources can be difficult, this Microsoft documentation is clarifying and can add some much needed visualization to the problem.

Adding a contact to the Skype for Business contact list

To add a new contact to the Skype for Business contact list with UCWA 2.0, a POST request will be made to the "people" resource myGroupMemberships. This path will look something like 
This path should be appended to the end of the UCWA application resource URL, such as:
The URI of the new contact will be passed as a parameter in this URL. So, if the contact's URI is, it will look something like:

There is an option to create the new contact in a specific group by including the ID of the group the contact should be added to. This demonstration doesn't include the group ID, so the contact is added to the default group. In the test cases, this was the group "Other Contacts".

All requests to UCWA resources require a bearer token to be present in the authentication header. Also, because the myGroupMemberships resource that's being accessed is in UCWA version 2.0, this version needs to be specified in the POST request with the "X-MS-RequiresMinResourceVersion" header, such as
float version = 2.0F;
client.DefaultRequestHeaders.Add("X-MS-RequiresMinResourceVersion", version.ToString());
If this POST request is made to the correct application URL with the bearer token, and version header, the new contact should appear in the authenticated user's Skype for Business client almost immediately. In rare cases, it might be necessary to log-out and then back in to see the changes.

This MSDN forum post was very helpful for this blog.


UCWA 2.0 and Skype for Business online: Create an Azure AD application

UCWA 2.0

Unified Communications Web API (UCWA) 2.0 is the first officially supported API for Skype for Business online. If an application is looking to talk to Skype for Business on Office 365 this is the way to do it, albeit limited. UCWA 2.0 exposes some, but not all, interactions with Skype that may be desired. For example, groups are a read-only resource in this version. While it might be desired to create a new group in a Skype for Business contact list, this is not possible in UCWA 2.0.

Create an Azure AD application for Skype for Business online

These steps will outline how to create an Azure AD (AAD) application that exposes the Skype for Business online API. Follow the steps from both sections in these directions from Microsoft. Make the following modification. At step 9, under "Register your application with Azure AD", select as many of the Delegated permissions as desired. For example, the permission "Read and manage Skype for Business user cont..." is required to get the Skype for Business contacts and to add new contacts to the buddy list. If you're curious to learn more about the difference between Application and Delegated permissions read this page.


Thursday, May 12, 2016

Stay connected with your University with just a single click!

Instant Chime addresses the needs of a well-known University, providing them the power to connect with their students in a more efficient way. Chime has empowered their service desk so that students get the help they need faster, eliminating the frustration of waiting. Universities realize that students do not want to waste time searching for answers to issues that could be addressed in minutes. Instant Chime is a simple click-to-chat help desk resolution tool for the productive student.

The IT Computer Support Coordinator with the University using Chime recently stated, “We have been using Chime to support our student population in the library. Since the library has over 300 computers across three floors and we are located on the first floor, Chime has allowed us to provide click-to-chat support to students at various areas in the library. We use it to answer questions, or dispatch a technician to meet with the student. It allows the student to not have to pack everything up then walk over to see us.”

Screen Shot Below:

For more questions visit:

Monday, April 25, 2016

Creating Outages in Chime

In Chime, you're now able to create outages displaying them in both the web client and system/queue dashboards. You also have the ability to turn an outage into an alert.

Screenshots showing outages being used in Chime:

For more on outages visit:

Thursday, April 21, 2016

Instant Login Manager for Lync and Skype for Business

Instant Login Manager is a simple app that quickly lets you switch between your Lync and Skype for Business accounts without having to manually sign out of one and into another.
This is perfect for testing Lync accounts that are used by systems or switching between test and production accounts.
Add a new profile by entering your Lync or Skype for Business credentials. Then you can switch back and forth between your profiles at the touch of a button.
Instant Login Manager Screenshot

 Instant Login Manager Demo