Skip to content

Commit

Permalink
CON-2182 Conftent api for employer finance
Browse files Browse the repository at this point in the history
  • Loading branch information
ben1stone-leftdfe committed Aug 13, 2020
1 parent 0a35f7a commit 84d4b36
Show file tree
Hide file tree
Showing 20 changed files with 416 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public static IContainer Initialize()
c.AddRegistry<DefaultRegistry>();
c.AddRegistry<EmployerFeaturesAuthorizationRegistry>();
c.AddRegistry<EmployerUserRolesAuthorizationRegistry>();
c.AddRegistry<ContentApiClientRegistry>();
});
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using SFA.DAS.EmployerFinance.Configuration;
using MediatR;
using SFA.DAS.EmployerFinance.Configuration;
using SFA.DAS.EmployerFinance.Helpers;
using SFA.DAS.EmployerFinance.Queries.GetClientContent;
using SFA.DAS.MA.Shared.UI.Configuration;
using SFA.DAS.MA.Shared.UI.Models;
using SFA.DAS.MA.Shared.UI.Models.Links;
Expand Down Expand Up @@ -121,5 +124,19 @@ public static ICookieBannerViewModel GetCookieBannerViewModel(this HtmlHelper ht
}
);
}

public static MvcHtmlString GetClientContentByType(this HtmlHelper html, string type, bool useLegacyStyles = false)
{
var mediator = DependencyResolver.Current.GetService<IMediator>();

var response = AsyncHelper.RunSync(() => mediator.SendAsync(new GetClientContentRequest
{
UseLegacyStyles = useLegacyStyles,
ContentType = type
}));

var content = response;
return MvcHtmlString.Create(content.Content);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@

@if (HttpContext.Current.User.Identity.IsAuthenticated)
{
@Html.Partial("_COVID19GuidanceBanner")
@Html.GetClientContentByType("banner", useLegacyStyles: true)
}

@Html.Partial(@"_SuccessMessage", Model as OrchestratorResponse)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using SFA.DAS.EmployerFinance.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SFA.DAS.EmployerFinance.Configuration
{
public class ContentClientApiConfiguration : IContentClientApiConfiguration
{
public string ApiBaseUrl { get; set; }
public string Tenant { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string IdentifierUri { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,6 @@ public class EmployerFinanceConfiguration : ITopicMessagePublisherConfiguration
public string ZenDeskSnippetKey { get; set; }
public string ZenDeskSectionId { get; set; }
public string ZenDeskCobrowsingSnippetKey { get; set; }
public ContentClientApiConfiguration ContentApi { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//using SFA.DAS.EmployerAccounts.Configuration;
using SFA.DAS.EmployerFinance.Configuration;
using SFA.DAS.EmployerFinance.Interfaces;
using SFA.DAS.EmployerFinance.Services;
using SFA.DAS.Http;
using SFA.DAS.Http.TokenGenerators;
using SFA.DAS.NLog.Logger.Web.MessageHandlers;
using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SFA.DAS.EmployerFinance.DependencyResolution
{
public class ContentApiClientRegistry : Registry
{
public ContentApiClientRegistry()
{
For<ContentClientApiConfiguration>().Use(c => c.GetInstance<EmployerFinanceConfiguration>().ContentApi);
For<IContentClientApiConfiguration>().Use(c => c.GetInstance<ContentClientApiConfiguration>());
For<IClientContentApiClient>().Use<ClientContentApiClient>().Ctor<HttpClient>().Is(c => CreateClient(c));
}
private HttpClient CreateClient(IContext context)
{
var config = context.GetInstance<EmployerFinanceConfiguration>().ContentApi;

HttpClient httpClient = new HttpClientBuilder()
.WithBearerAuthorisationHeader(new AzureActiveDirectoryBearerTokenGenerator(config))
.WithHandler(new RequestIdMessageRequestHandler())
.WithHandler(new SessionIdMessageRequestHandler())
.WithDefaultHeaders()
.Build();

return httpClient;
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public byte[] GetFileData(IEnumerable<TransactionDownloadLine> transactions)

var csvContent = builder.ToString();

return Encoding.UTF8.GetBytes(csvContent);
return System.Text.Encoding.UTF8.GetBytes(csvContent);
}

protected abstract string CreateHeaders();
Expand Down
49 changes: 49 additions & 0 deletions src/SFA.DAS.EmployerFinance/Helpers/AsyncHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SFA.DAS.EmployerFinance.Helpers
{
// Borrowed from https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs
// [ASP.NET Identity]
// Copyright(c) Microsoft Corporation
// All rights reserved.
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

public static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None,
TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);

public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
var cultureUi = CultureInfo.CurrentUICulture;
var culture = CultureInfo.CurrentCulture;
return _myTaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap().GetAwaiter().GetResult();
}

public static void RunSync(Func<Task> func)
{
var cultureUi = CultureInfo.CurrentUICulture;
var culture = CultureInfo.CurrentCulture;
_myTaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap().GetAwaiter().GetResult();
}
}
}
2 changes: 1 addition & 1 deletion src/SFA.DAS.EmployerFinance/Http/HttpClientWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task<string> SendMessage<T>(T content, string url)
var serializeObject = JsonConvert.SerializeObject(content);
var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(serializeObject, Encoding.UTF8, "application/json")
Content = new StringContent(serializeObject, System.Text.Encoding.UTF8, "application/json")
});
await EnsureSuccessfulResponse(response);

Expand Down
15 changes: 15 additions & 0 deletions src/SFA.DAS.EmployerFinance/Interfaces/ICacheStorageService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SFA.DAS.EmployerFinance.Interfaces
{
public interface ICacheStorageService
{
Task Save<T>(string key, T item, int expirationInMinutes);
Task Delete(string key);
bool TryGet(string key, out string value);
}
}
13 changes: 13 additions & 0 deletions src/SFA.DAS.EmployerFinance/Interfaces/IClientContentApiClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SFA.DAS.EmployerFinance.Interfaces
{
public interface IClientContentApiClient
{
Task<string> Get(string type, string applicationId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Threading.Tasks;

namespace SFA.DAS.EmployerFinance.Interfaces
{
public interface IClientContentService
{
Task<string> Get(string type, string applicationId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using SFA.DAS.Http.Configuration;

namespace SFA.DAS.EmployerFinance.Interfaces
{
public interface IContentClientApiConfiguration : IAzureActiveDirectoryClientConfiguration
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using MediatR;

namespace SFA.DAS.EmployerFinance.Queries.GetClientContent
{
public class GetClientContentRequest : IAsyncRequest<GetClientContentResponse>
{
public string ContentType { get; set; }
public bool UseLegacyStyles { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System;
using System.Net.Http;
using System.Threading.Tasks;
using MediatR;
using SFA.DAS.Authentication.Extensions.Legacy;
using SFA.DAS.EmployerFinance.Configuration;
using SFA.DAS.EmployerFinance.Interfaces;
//using SFA.DAS.EmployerAccounts.Configuration;
//using SFA.DAS.EmployerAccounts.Interfaces;
using SFA.DAS.NLog.Logger;
using SFA.DAS.Validation;

namespace SFA.DAS.EmployerFinance.Queries.GetClientContent
{
public class GetClientContentRequestHandler : IAsyncRequestHandler<GetClientContentRequest, GetClientContentResponse>
{
private readonly IValidator<GetClientContentRequest> _validator;
private readonly ILog _logger;
private readonly IClientContentService _service;
private readonly ICacheStorageService _cacheStorageService;
private readonly EmployerFinanceConfiguration _employerFinanceConfiguration;

public GetClientContentRequestHandler(
IValidator<GetClientContentRequest> validator,
ILog logger,
IClientContentService service,
ICacheStorageService cacheStorageService,
//EmployerAccountsConfiguration employerAccountsConfiguration)
EmployerFinanceConfiguration employerFinanceConfiguration
)
{
_validator = validator;
_logger = logger;
_service = service;
_cacheStorageService = cacheStorageService;
_employerFinanceConfiguration = employerFinanceConfiguration;
}

public async Task<GetClientContentResponse> Handle(GetClientContentRequest message)
{
var validationResult = _validator.Validate(message);

if (!validationResult.IsValid())
{
throw new InvalidRequestException(validationResult.ValidationDictionary);
}

//var applicationId = message.UseLegacyStyles ? _employerFinanceConfiguration.ApplicationId + "-legacy" : _employerFinanceConfiguration.ApplicationId;

//var applicationId = message.UseLegacyStyles ? "das-employeraccounts-web-legacy" : "das-employeraccounts-web";
var applicationId = message.UseLegacyStyles ? "das-employerfinance-web-legacy" : "das-employerfinance-web";

var cacheKey = $"{applicationId}_{message.ContentType}".ToLowerInvariant();

try
{
if (_cacheStorageService.TryGet(cacheKey, out string cachedContentBanner))
{
return new GetClientContentResponse
{
Content = cachedContentBanner
};
}

var contentBanner = await _service.Get(message.ContentType, applicationId);

if (contentBanner != null)
{
await _cacheStorageService.Save(cacheKey, contentBanner, 1);
}
return new GetClientContentResponse
{
Content = contentBanner
};
}
catch (Exception ex)
{
_logger.Error(ex, $"Failed to get Content for {cacheKey}");

return new GetClientContentResponse
{
HasFailed = true
};
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Threading.Tasks;
using SFA.DAS.Validation;

namespace SFA.DAS.EmployerFinance.Queries.GetClientContent
{
public class GetClientContentRequestValidator : IValidator<GetClientContentRequest>
{
public ValidationResult Validate(GetClientContentRequest item)
{
var validationResult = new ValidationResult();

if (string.IsNullOrEmpty(item.ContentType))
{
validationResult.AddError(nameof(item.ContentType), "Type has not been supplied");
}
return validationResult;
}

public Task<ValidationResult> ValidateAsync(GetClientContentRequest item)
{
return Task.FromResult(Validate(item));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace SFA.DAS.EmployerFinance.Queries.GetClientContent
{
public class GetClientContentResponse
{
public string Content { get; set; }
public bool HasFailed { get; set; }
}
}
Loading

0 comments on commit 84d4b36

Please sign in to comment.