public async Task <Contact?> GetContactByEmailAsync(string email, CancellationToken cancellationToken = default) { return(await m_cache.GetOrCreateAsync(email, async entry => { entry.SetSlidingExpiration(TimeSpan.FromMinutes(120)); var filter = new CrmSearchOptions { FilterGroups = { new CrmSearchFilterGroups { Filters = { new CrmSearchFilter { PropertyName = "email", Operator = "EQ", Value = email, }, }, }, }, Properties = DomainModelMapper.GetPropertyNames(new Contact()), Limit = 1, }; var json = JsonConvert.SerializeObject(filter, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy(), }, NullValueHandling = NullValueHandling.Ignore, }); using var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await RequestWithRetriesAsync( async cancellationToken => await m_client.PostAsync("/crm/v3/objects/contacts/search", content, cancellationToken), cancellationToken); if (response.StatusCode == HttpStatusCode.NotFound) { return null; } await response.EnsureSuccessStatusCodeWithResponseBodyInException(); var searchResults = JsonConvert.DeserializeObject <GetCrmObjectsResult>(await response.Content.ReadAsStringAsync()); return DomainModelMapper.MapDomainModel <Contact>(searchResults.Results.FirstOrDefault()); })); }
public async Task HydrateCompaniesCacheAsync(CancellationToken cancellationToken = default) { var cacheOptions = new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(120), }; var parameters = new Dictionary <string, string> { { "limit", "100" }, { "properties", string.Join(",", DomainModelMapper.GetPropertyNames(new Company())) }, }; var uri = new Uri(QueryHelpers.AddQueryString($"{m_client.BaseAddress}crm/v3/objects/companies", parameters)); while (true) { var response = await RequestWithRetriesAsync( async cancellationToken => await m_client.GetAsync(uri, cancellationToken), cancellationToken); await response.EnsureSuccessStatusCodeWithResponseBodyInException(); var companies = JsonConvert.DeserializeObject <GetCrmObjectsResult>(await response.Content.ReadAsStringAsync()); foreach (var company in companies.Results) { if (company.Properties != null && company.Properties.ContainsKey("account_id") && !company.Properties.Value <string>("account_id").IsNullOrEmpty()) { m_cache.Set(company.Properties.Value <string>("account_id"), DomainModelMapper.MapDomainModel <Company>(company), cacheOptions); } } if (companies.Paging == null) { break; } uri = new Uri(companies.Paging.Next.Link); } }