public ActionResult GetPolicy(string slug) { MicrosoftDynamicsCRMadoxioPolicydocument policyDocument = null; string cacheKey = CacheKeys.PolicyDocumentPrefix + slug; if (!_cache.TryGetValue(cacheKey, out policyDocument)) { // Key not in cache, so get data. policyDocument = _dynamicsClient.GetPolicyDocumentBySlug(slug); // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time .SetAbsoluteExpiration(TimeSpan.FromMinutes(5)); // Save data in cache. _cache.Set(cacheKey, policyDocument, cacheEntryOptions); } if (policyDocument == null) { return(new NotFoundResult()); } else { return(Json(policyDocument.ToViewModel())); } }
public static MicrosoftDynamicsCRMadoxioPolicydocument GetPolicyDocumentBySlug(this IDynamicsClient dynamicsClient, string slug) { MicrosoftDynamicsCRMadoxioPolicydocument result = null; slug = slug.Replace("'", "''"); string filter = "adoxio_slug eq '" + slug + "'"; var pdgrm = dynamicsClient.Policydocuments.Get(filter: filter); result = pdgrm.Value .FirstOrDefault(); return(result); }
public static ViewModels.PolicyDocumentSummary ToSummaryViewModel(this MicrosoftDynamicsCRMadoxioPolicydocument policyDocument) { ViewModels.PolicyDocumentSummary result = null; if (policyDocument != null) { result = new ViewModels.PolicyDocumentSummary { slug = policyDocument.AdoxioSlug, menuText = policyDocument.AdoxioMenutext }; } return(result); }
/// <summary> /// Add a PolicyDocument /// </summary> /// <param name="context"></param> /// <param name="PolicyDocument"></param> public static void AddPolicyDocument(this IDynamicsClient dynamicsClient, MicrosoftDynamicsCRMadoxioPolicydocument PolicyDocument) { if (PolicyDocument != null) { try { dynamicsClient.Policydocuments.Create(PolicyDocument); } catch (HttpOperationException) { } } }
public static MicrosoftDynamicsCRMadoxioPolicydocument GetPolicyDocumentBySlug(this IDynamicsClient dynamicsClient, string slug) { MicrosoftDynamicsCRMadoxioPolicydocument result = null; try { slug = slug.Replace("'", "''"); string filter = "adoxio_slug eq '" + slug + "'"; result = dynamicsClient.Policydocuments.Get(filter: filter).Value .FirstOrDefault(); } catch (OdataerrorException) { result = null; } return(result); }
public static void ProcessTemplate(this IDynamicsClient dynamicsClient, MicrosoftDynamicsCRMadoxioPolicydocument document) { string body = document.AdoxioBody; if (body != null) { // start by scanning the document for blocks. int startRepeaterPos = body.IndexOf(REPEATER_START_TAG); if (startRepeaterPos > -1) { int endRepeaterStartTagPos = body.IndexOf(">", startRepeaterPos); if (endRepeaterStartTagPos > -1) { int endRepeaterPos = body.IndexOf(REPEATER_END_TAG); } } } document.AdoxioBody = body; }
/// <summary> /// Convert a given voteQuestion to a ViewModel /// </summary> public static ViewModels.PolicyDocument ToViewModel(this MicrosoftDynamicsCRMadoxioPolicydocument policyDocument) { ViewModels.PolicyDocument result = null; if (policyDocument != null) { result = new ViewModels.PolicyDocument { id = policyDocument.AdoxioPolicydocumentid, slug = policyDocument.AdoxioSlug, title = policyDocument.AdoxioName, category = policyDocument.AdoxioCategory, menuText = policyDocument.AdoxioMenutext, body = policyDocument.AdoxioBody }; if (policyDocument.AdoxioDisplayorder != null) { result.displayOrder = (int)policyDocument.AdoxioDisplayorder; } } return(result); }
/// <summary> /// Adds a jurisdiction to the system, only if it does not exist. /// </summary> private static void AddInitialPolicyDocument(this IDynamicsClient dynamicsClient, ViewModels.PolicyDocument initialPolicyDocument) { MicrosoftDynamicsCRMadoxioPolicydocument PolicyDocument = dynamicsClient.GetPolicyDocumentBySlug(initialPolicyDocument.slug); if (PolicyDocument != null) { return; } PolicyDocument = new MicrosoftDynamicsCRMadoxioPolicydocument { AdoxioSlug = initialPolicyDocument.slug, AdoxioName = initialPolicyDocument.title, AdoxioMenutext = initialPolicyDocument.menuText, AdoxioCategory = initialPolicyDocument.category, AdoxioBody = initialPolicyDocument.body, AdoxioDisplayorder = initialPolicyDocument.displayOrder }; dynamicsClient.AddPolicyDocument(PolicyDocument); }
public ActionResult GetPolicy(string slug) { MicrosoftDynamicsCRMadoxioPolicydocument policyDocument = null; bool fetchDocument = false; string cacheKey = CacheKeys.PolicyDocumentPrefix + slug; string cacheAgeKey = CacheKeys.PolicyDocumentCategoryPrefix + slug + "_dto"; if (!_cache.TryGetValue(cacheKey, out policyDocument)) // item is not in cache at all, fetch. { fetchDocument = true; } else { DateTimeOffset dto = DateTimeOffset.Now; // fetch the age of the cache item from the cache if (!_cache.TryGetValue(cacheAgeKey, out dto)) // unable to get cache age, fetch. { fetchDocument = true; } else { TimeSpan age = DateTimeOffset.Now - dto; if (age.TotalMinutes > 10) // More than 10 minutes old, fetch. { fetchDocument = true; } } } if (fetchDocument) { try { policyDocument = _dynamicsClient.GetPolicyDocumentBySlug(slug); if (policyDocument != null) // handle case where the document is missing. { // Set cache options. var newCacheEntryOptions = new MemoryCacheEntryOptions() // Set the cache to expire far in the future. .SetAbsoluteExpiration(TimeSpan.FromDays(365 * 5)); // Save data in cache. _cache.Set(cacheKey, policyDocument, newCacheEntryOptions); _cache.Set(cacheAgeKey, DateTimeOffset.Now, newCacheEntryOptions); } else { _logger.LogError($"Unable to get Policy Document {slug} - does it exist?"); } } catch (HttpOperationException httpOperationException) { // this will gracefully handle situations where Dynamics is not available however we have a cache version. _logger.LogError(httpOperationException, "Error getting policy document"); } catch (Exception e) { // unexpected exception _logger.LogError(e, "Unknown error occured"); } } if (policyDocument == null) { return(new NotFoundResult()); } return(new JsonResult(policyDocument.ToViewModel())); }
/// <summary> /// Update entity in adoxio_policydocuments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPolicydocumentid'> /// key: adoxio_policydocumentid of adoxio_policydocument /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse UpdateWithHttpMessages(this IPolicydocuments operations, string adoxioPolicydocumentid, MicrosoftDynamicsCRMadoxioPolicydocument body, Dictionary <string, List <string> > customHeaders = null) { return(operations.UpdateWithHttpMessagesAsync(adoxioPolicydocumentid, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_policydocuments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPolicydocumentid'> /// key: adoxio_policydocumentid of adoxio_policydocument /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IPolicydocuments operations, string adoxioPolicydocumentid, MicrosoftDynamicsCRMadoxioPolicydocument body, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(adoxioPolicydocumentid, body, null, cancellationToken).ConfigureAwait(false)).Dispose(); }
/// <summary> /// Update entity in adoxio_policydocuments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='adoxioPolicydocumentid'> /// key: adoxio_policydocumentid of adoxio_policydocument /// </param> /// <param name='body'> /// New property values /// </param> public static void Update(this IPolicydocuments operations, string adoxioPolicydocumentid, MicrosoftDynamicsCRMadoxioPolicydocument body) { operations.UpdateAsync(adoxioPolicydocumentid, body).GetAwaiter().GetResult(); }
/// <summary> /// Add new entity to adoxio_policydocuments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> public static HttpOperationResponse <MicrosoftDynamicsCRMadoxioPolicydocument> CreateWithHttpMessages(this IPolicydocuments operations, MicrosoftDynamicsCRMadoxioPolicydocument body, string prefer = "return=representation", Dictionary <string, List <string> > customHeaders = null) { return(operations.CreateWithHttpMessagesAsync(body, prefer, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult()); }
/// <summary> /// Add new entity to adoxio_policydocuments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <MicrosoftDynamicsCRMadoxioPolicydocument> CreateAsync(this IPolicydocuments operations, MicrosoftDynamicsCRMadoxioPolicydocument body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Add new entity to adoxio_policydocuments /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='body'> /// New entity /// </param> /// <param name='prefer'> /// Required in order for the service to return a JSON representation of the /// object. /// </param> public static MicrosoftDynamicsCRMadoxioPolicydocument Create(this IPolicydocuments operations, MicrosoftDynamicsCRMadoxioPolicydocument body, string prefer = "return=representation") { return(operations.CreateAsync(body, prefer).GetAwaiter().GetResult()); }
/// <summary> /// Update entity in adoxio_policydocuments /// </summary> /// <param name='adoxioPolicydocumentid'> /// key: adoxio_policydocumentid of adoxio_policydocument /// </param> /// <param name='body'> /// New property values /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> UpdateWithHttpMessagesAsync(string adoxioPolicydocumentid, MicrosoftDynamicsCRMadoxioPolicydocument body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioPolicydocumentid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioPolicydocumentid"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("adoxioPolicydocumentid", adoxioPolicydocumentid); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_policydocuments({adoxio_policydocumentid})").ToString(); _url = _url.Replace("{adoxio_policydocumentid}", System.Uri.EscapeDataString(adoxioPolicydocumentid)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }