Last active
August 29, 2015 14:02
-
-
Save ThorstenHans/0efd53eca4fc77008e9e to your computer and use it in GitHub Desktop.
O365Crud
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class ContactsRepository : IContactsRepository<IContact> | |
{ | |
private ExchangeClient _exchangeClient; | |
private const string ExchangeResourceId = "https://outlook.office365.com"; | |
private const string ExchangeServiceRoot = "https://outlook.office365.com/ews/odata"; | |
private const int PageSize = 50; | |
private async Task<ExchangeClient> EnsureExchangeClient() | |
{ | |
if (_exchangeClient != null) | |
return _exchangeClient; | |
Authenticator authenticator = new Authenticator(); | |
var authInfo = await authenticator.AuthenticateAsync(ExchangeResourceId); | |
_exchangeClient = new ExchangeClient(new Uri(ExchangeServiceRoot), authInfo.GetAccessToken); | |
return _exchangeClient; | |
} | |
public async Task<IContact> GetById(string id) | |
{ | |
var client = await EnsureExchangeClient(); | |
return await client.Me | |
.Contacts | |
.Where(c => c.Id.Equals(id)) | |
.ExecuteSingleAsync(); | |
} | |
public async Task<IEnumerable<IContact>> Get(int pageNumber) | |
{ | |
var skipItems = pageNumber*PageSize; | |
var client = await EnsureExchangeClient(); | |
var contacts = await client.Me | |
.Contacts | |
.OrderBy(c => c.DisplayName) | |
.Skip(skipItems) | |
.ExecuteAsync(); | |
return contacts.CurrentPage; | |
} | |
public async void Create(IContact instance) | |
{ | |
if (instance != null) | |
{ | |
throw new ArgumentNullException("instance"); | |
} | |
var client = await EnsureExchangeClient(); | |
await client.Me | |
.Contacts | |
.AddContactAsync(instance); | |
} | |
public async void Update(IContact instance) | |
{ | |
if (instance != null) | |
{ | |
throw new ArgumentNullException("instance"); | |
} | |
var client = await EnsureExchangeClient(); | |
await instance.UpdateAsync(); | |
} | |
public async void Delete(IContact instance) | |
{ | |
if (instance != null) | |
{ | |
throw new ArgumentNullException("instance"); | |
} | |
var client = await EnsureExchangeClient(); | |
await instance.DeleteAsync(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal interface IContactsRepository<T> | |
{ | |
Task<T> GetById(string id); | |
Task<IEnumerable<T>> Get(int pageNumber); | |
void Create(T instance); | |
void Update(T instance); | |
void Delete(T instance); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment