/// <summary> /// Load User from database using their userId and guid /// </summary> /// <param name="context"></param> /// <param name="userId"></param> /// <param name="guid"></param> /// <returns></returns> public static async Task <User> LoadUser(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string userId, string guid = null) { User user = null; if (!string.IsNullOrEmpty(guid)) { user = await system.GetUserByGuid(distributedCache, guid); } if (user == null) { user = await system.GetUserBySmUserId(distributedCache, userId); } if (user == null) { return(null); } if (guid == null) { return(user); } if (!user.ContactId.ToString().Equals(guid, StringComparison.OrdinalIgnoreCase)) { // invalid account - guid doesn't match user credential return(null); } return(user); }
public static Microsoft.Dynamics.CRM.System GetCdsContext() { var cdsConfig = GetCdsConfig(); var cdsContext = new Microsoft.Dynamics.CRM.System(new Uri($"{cdsConfig.UriString}/api/data/v9.0/")); var client = new System.Net.Http.HttpClient(); var dictionary = new Dictionary <string, string>(); dictionary["grant_type"] = "password"; dictionary["resource"] = cdsConfig.UriString; dictionary["username"] = cdsConfig.User; dictionary["password"] = cdsConfig.Password; dictionary["client_id"] = cdsConfig.NativeAppId; var response = client.PostAsync("https://login.microsoftonline.com/common/oauth2/token", new System.Net.Http.FormUrlEncodedContent(dictionary)).Result; if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new InvalidOperationException("Unable to get token."); } var responseString = response.Content.ReadAsStringAsync().Result; var token = Newtonsoft.Json.Linq.JObject.Parse(responseString); var accessToken = (string)token.SelectToken("access_token"); cdsContext.BuildingRequest += (sender, eventArgs) => { eventArgs.Headers["Authorization"] = "Bearer " + accessToken; }; return(cdsContext); }
/// <summary> /// Returns a User based on the Siteminder ID /// </summary> /// <param name="context"></param> /// <param name="smUserId"></param> /// <returns></returns> public static async Task <User> GetUserBySmUserId(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string smUserId) { User user = null; Contact contact = await system.GetContactBySiteminderGuid(distributedCache, smUserId); if (contact != null) { user = new User(); user.FromContact(contact); } return(user); }
/// <summary> /// Returns a User based on the guid /// </summary> /// <param name="context"></param> /// <param name="guid"></param> /// <returns></returns> public static async Task <User> GetUserByGuid(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string guid) { Guid id = new Guid(guid); User user = null; Contact contact = await system.GetContactById(distributedCache, id); if (contact != null) { user.FromContact(contact); } return(user); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); var serviceRoot = "https://ss2021pc.crm11.dynamics.com/api/data/v9.2"; var context = new Microsoft.Dynamics.CRM.System(new Uri(serviceRoot)); var contacts = (from c in context.contacts where c.firstname.StartsWith("Rob") select new { c.fullname }) .Take(10).AsEnumerable(); return(req.CreateResponse(HttpStatusCode.OK, "Hello " + String.Join(", ", contacts))); }
public static Contact GetContact(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string siteminderId) { Contact result = null; string key = "Contact_" + siteminderId; // first look in the cache. string temp = distributedCache.GetString(key); if (!string.IsNullOrEmpty(temp)) { result = JsonConvert.DeserializeObject <Contact>(temp); } else { } return(result); }
/// <summary> /// Get a contact by their Guid /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="id"></param> /// <returns></returns> public static async Task <Contact> GetContactById(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, Guid id) { Contact result = null; string key = "Contact_" + id.ToString(); // first look in the cache. string temp = null; if (distributedCache != null) { temp = distributedCache.GetString(key); } if (!string.IsNullOrEmpty(temp)) { result = JsonConvert.DeserializeObject <Contact>(temp); } else { // fetch from Dynamics. try { result = await system.Contacts.ByKey(id).GetValueAsync(); } catch (DataServiceQueryException dsqe) { if (dsqe.Message.Contains("Does Not Exist")) { result = null; } else { throw; } } if (result != null && distributedCache != null) { // store the contact data. string cacheValue = JsonConvert.SerializeObject(result); distributedCache.SetString(key, cacheValue); } } return(result); }
/// <summary> /// Utility method to call Dynamics <see langword="async"/>, with a delay to compensate for timing issues. /// </summary> /// <param name="system"></param> /// <param name="options"></param> /// <returns>dsr</returns> public static DataServiceResponse SaveChangesSynchronous(this Microsoft.Dynamics.CRM.System system, SaveChangesOptions options) { Task <DataServiceResponse> t = system.SaveChangesAsync(options); System.Threading.Thread.Sleep(5000); t.Wait(); if (t.IsFaulted) { throw new Exception("Error save changes failed:" + t.Exception.Message); } else if (!t.IsCompletedSuccessfully) { throw new Exception("Error save changes failed with no message"); } DataServiceResponse dsr = t.Result; return(dsr); }
/// <summary> /// Get a contact by their Siteminder ID /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="siteminderId"></param> /// <returns></returns> public static async Task <Contact> GetContactBySiteminderGuid(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string siteminderId) { Contact result = null; string key = "Contact_" + siteminderId; // first look in the cache. string temp = null; if (distributedCache != null) { temp = distributedCache.GetString(key); } if (!string.IsNullOrEmpty(temp)) { Guid id = new Guid(temp); result = await system.GetContactById(distributedCache, id); } else { try { var contacts = await system.Contacts.AddQueryOption("$filter", "adoxio_externalid eq '" + siteminderId + "'").ExecuteAsync(); result = contacts.FirstOrDefault(); if (result != null && distributedCache != null) { // store the contact data. Guid id = (Guid)result.Contactid; distributedCache.SetString(key, id.ToString()); // update the cache for the contact. string contact_key = "Contact_" + id.ToString(); string cacheValue = JsonConvert.SerializeObject(result); distributedCache.SetString(contact_key, cacheValue); } } catch (DataServiceQueryException dsqe) { result = null; } } return(result); }
public static Microsoft.Dynamics.CRM.System GetCdsContext() { var cdsConfig = GetCdsConfig(); var cdsContext = new Microsoft.Dynamics.CRM.System(new Uri($"{cdsConfig.UriString}/api/data/v9.0/")); var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext( "https://login.windows.net/common", false); var result = Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions.AcquireTokenAsync( authContext, cdsConfig.UriString, cdsConfig.NativeAppId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential( cdsConfig.User, cdsConfig.Password)).Result; cdsContext.BuildingRequest += (sender, eventArgs) => { eventArgs.Headers["Authorization"] = "Bearer " + result.AccessToken; }; return(cdsContext); }
/// <summary> /// Get a Account by their Guid /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="id"></param> /// <returns></returns> public static async Task <Account> GetAccountById(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, Guid id) { Account result = null; // fetch from Dynamics. try { result = await system.Accounts.ByKey(id).GetValueAsync(); } catch (DataServiceQueryException dsqe) { if (dsqe.Message.Contains("Does Not Exist") || dsqe.InnerException.Message.Contains("Does Not Exist")) { result = null; } else { throw; } } return(result); }
/// <summary> /// Get a contact by their Guid /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="id"></param> /// <returns></returns> public static async Task <Adoxio_licencetype> GetLicenceTypeById(this Microsoft.Dynamics.CRM.System system, Guid id) { Adoxio_licencetype result = null; // fetch from Dynamics. try { result = await system.Adoxio_licencetypes.ByKey(id).GetValueAsync(); } catch (DataServiceQueryException dsqe) { if (dsqe.Message.Contains("Does Not Exist")) { result = null; } else { throw; } } return(result); }
/// <summary> /// Get picklist options for a given field /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="datafield"></param> /// <returns></returns> public static async Task <List <Public.ViewModels.OptionMetadata> > GetPicklistOptions(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string datafield) { List <Public.ViewModels.OptionMetadata> result = null; string key = "GlobalOptionSetDefinition_" + datafield; // first look in the cache. string temp = null; if (distributedCache != null) { temp = distributedCache.GetString(key); } if (!string.IsNullOrEmpty(temp)) { result = JsonConvert.DeserializeObject <List <Public.ViewModels.OptionMetadata> >(temp); } else { // fetch from dynamics var source = system.GlobalOptionSetDefinitions; OptionSetMetadataBaseSingle optionSetMetadataBaseSingle = new OptionSetMetadataBaseSingle(source.Context, source.GetKeyPath("Name='" + datafield + "'")); OptionSetMetadata optionSetMetadata = (OptionSetMetadata)await optionSetMetadataBaseSingle.GetValueAsync(); if (optionSetMetadata != null) { // convert it to a list. result = new List <Public.ViewModels.OptionMetadata>(); foreach (Microsoft.Dynamics.CRM.OptionMetadata option in optionSetMetadata.Options) { result.Add(option.ToViewModel()); } } if (distributedCache != null) { // store the picklist data. string cacheValue = JsonConvert.SerializeObject(result); distributedCache.SetString(key, cacheValue); } } return(result); }
/// <summary> /// Get a dynamics application by their Guid /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="id"></param> /// <returns></returns> public static async Task <MicrosoftDynamicsCRMadoxioapplication> GetAdoxioApplicationById(this Microsoft.Dynamics.CRM.System system, Guid id) { MicrosoftDynamicsCRMadoxioapplication result = null; // fetch from Dynamics. try { result = await system.Adoxio_applications.ByKey(id).GetValueAsync(); } catch (DataServiceQueryException dsqe) { result = null; } return(result); }
/// <summary> /// Get a Account by their Guid /// </summary> /// <param name="system"></param> /// <param name="distributedCache"></param> /// <param name="id"></param> /// <returns></returns> public static async Task <Account> GetAccountBySiteminderBusinessGuid(this Microsoft.Dynamics.CRM.System system, IDistributedCache distributedCache, string siteminderId) { Account result = null; string key = "Account_" + siteminderId; // first look in the cache. string temp = null; if (distributedCache != null) { temp = distributedCache.GetString(key); } if (!string.IsNullOrEmpty(temp)) { result = JsonConvert.DeserializeObject <Account>(temp); } else { // fetch from Dynamics. try { var accounts = await system.Accounts.AddQueryOption("$filter", "adoxio_externalid eq '" + siteminderId + "'").ExecuteAsync(); if (accounts != null) { List <Account> results = new List <Account>(); foreach (var accountEntity in accounts) { results.Add(accountEntity); } if (results.Count == 0) { result = null; } else { result = results.First(); } } else { result = null; } } catch (DataServiceQueryException dsqe) { if (dsqe.Message.Contains("Does Not Exist")) { result = null; } else { throw; } } if (result != null && distributedCache != null) { // store the contact data. string cacheValue = JsonConvert.SerializeObject(result); distributedCache.SetString(key, cacheValue); } } return(result); }