A Pen by john Coxhead

Thumbnail
This awesome code was written by jcoxhead127, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright jcoxhead127 ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>A Pen by  john Coxhead</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/jcoxhead127/a-pen-by-john-coxhead-JWZrbo */
{
  "version": "1.0.0-*",

  "testRunner": "mstest",

  "dependencies": {
    "dotnet-test-mstest": "1.1.2-preview",
    "Moq": "4.5.28",
    "Schroders.UmbrellaFundService.DataContracts": "1.0.0-*",
    "Schroders.UmbrellaFundService.Repository": "1.0.0-*",
    "Schroders.Storage.Core": "1.0.0-6",
    "Schroders.Test.Infrastructure": "1.0.0-1",
    "Schroders.Storage.CouchbaseStorage": "1.0.0-9"
  },

  "frameworks": {
    "net461": {}
  }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Schroders.Storage.Core;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.Storage.Core.DataContracts;
using Schroders.Test.Infrastructure;

namespace Schroders.UmbrellaFundService.Repository.Tests
{
    [TestClass]
    public class UmbrellaFundWriteRepositoryTests : TestBase
    {
        private const string UmbrellaFundName = "Item Name";
        private const string UmbrellaFundCode = "testCode";

        [TestMethod]
        public void UmbrellaFundWriteRepository_CreateUmbrellaFund()
        {
            var documentStorageMock = new Mock<IDocumentStorage>();
            var documentStorageProviderMock = new Mock<IDocumentStorageProvider>();

            var umbrellaFund = new WriteUmbrellaFund { UmbrellaFundCode = UmbrellaFundCode, Name = UmbrellaFundName };

            documentStorageMock.Setup(x => x.CreateDocument(It.IsAny<string>(), umbrellaFund.UmbrellaFundCode, umbrellaFund)).Returns(new OperationResponse<WriteUmbrellaFund>
            {
                Success = true,
                Result = umbrellaFund
            });

            documentStorageProviderMock.Setup(x => x.GetDocumentStorage()).Returns(documentStorageMock.Object);

            var repository = new UmbrellaFundWriteRepository(documentStorageProviderMock.Object);

            repository.CreateUmbrellaFund(umbrellaFund);

            documentStorageMock.Verify(x =>
                x.CreateDocument(
                    It.IsNotNull<string>(),
                    It.IsNotNull<string>(),
                    It.Is<WriteUmbrellaFund>(p => p.Name == UmbrellaFundName && p.UmbrellaFundCode == UmbrellaFundCode)));
        }

        [TestMethod]
        public void UmbrellaFundWriteRepository_UpdateUmbrellaFund()
        {
            var documentStorageMock = new Mock<IDocumentStorage>();
            var documentStorageProviderMock = new Mock<IDocumentStorageProvider>();

            var umbrellaFund = new WriteUmbrellaFund { UmbrellaFundCode = UmbrellaFundCode, Name = UmbrellaFundName };

            documentStorageMock.Setup(x => x.UpdateDocument(It.IsAny<string>(), umbrellaFund.UmbrellaFundCode, umbrellaFund)).Returns(new OperationResponse<WriteUmbrellaFund>
            {
                Success = true,
                Result = umbrellaFund
            });

            documentStorageProviderMock.Setup(x => x.GetDocumentStorage()).Returns(documentStorageMock.Object);

            var repository = new UmbrellaFundWriteRepository(documentStorageProviderMock.Object);

            repository.UpdateUmbrellaFund(umbrellaFund);

            documentStorageMock.Verify(x =>
                x.UpdateDocument(
                    It.IsNotNull<string>(),
                    It.IsNotNull<string>(),
                    It.Is<WriteUmbrellaFund>(p => p.Name == UmbrellaFundName && p.UmbrellaFundCode == UmbrellaFundCode)));
        }
    }
}

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.Storage.CouchbaseDocumentStorage;
using Schroders.Storage.CouchbaseDocumentStorage.Configurations;
using Schroders.Test.Infrastructure;

namespace Schroders.UmbrellaFundService.Repository.Tests
{
    [Ignore]
    [TestClass]
    public class UmbrellaFundWriteRepositoryIntegrationTests : TestBase
    {
        private const string BucketName = "ProductMaster";
        private const string ServerUrl = "http://10.142.150.101:8091";

        [TestMethod]
        public void UmbrellaFundWriteRepository_CreateUmbrellaFund_IntegrationTest()
        {
            var storageProvider = GetCouchbaseStorageProvider();
            var writeRepository = new UmbrellaFundWriteRepository(storageProvider);

            const int index = 2;

            var writeUmbrellaFund = new WriteUmbrellaFund
            {
                UmbrellaFundCode = $"UmbrellaFundCode_{index}",
                PlatformUmbrellaCode = $"PlatformUmbrellaCode_{index}",
                PlatformSystemSourceCode = $"PlatformSystemSourceCode_{index}",
                ManagementCompanyCode = $"ManagementCompanyCode_{index}",
                Name = $"Test UmbrellaFund Name_{index}",
                CountryOfDomicile = "CountryOfDomicile",
                TypeOfVehicle = $"TypeOfVehicle_{index}"
            };

            writeRepository.CreateUmbrellaFund(writeUmbrellaFund);

            var readRepository = new UmbrellaFundReadRepository(storageProvider);
            var readUmbrellaFund = readRepository.GetUmbrellaFund(writeUmbrellaFund.UmbrellaFundCode);

            Assert.IsNotNull(readUmbrellaFund);
            Assert.AreEqual(readUmbrellaFund.UmbrellaFundCode, writeUmbrellaFund.UmbrellaFundCode);
        }

        private CouchbaseStorageProvider GetCouchbaseStorageProvider()
        {
            var optionsMock = new Mock<IOptions<CouchbaseStorageConfiguration>>();
            var couchbaseConfiguration = new CouchbaseStorageConfiguration
            {
                ServerUrl = new List<string> { ServerUrl },
                BucketName = BucketName
            };
            optionsMock.Setup(x => x.Value).Returns(couchbaseConfiguration);

            var storageProvider = new CouchbaseStorageProvider(optionsMock.Object, new ClusterProvider());
            return storageProvider;
        }
    }
}


using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Schroders.Storage.Core;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.Storage.Core.DataContracts;
using Schroders.Test.Infrastructure;

namespace Schroders.UmbrellaFundService.Repository.Tests
{
    [TestClass]
    public class UmbrellaFundReadRepositoryTests : TestBase
    {
        private const string UmbrellaFundCode = "testCode";

        [TestMethod]
        public void UmbrellaFundReadRepository_GetUmbrellaFund()
        {
            var documentStorageMock = new Mock<IDocumentStorage>();
            var documentStorageProviderMock = new Mock<IDocumentStorageProvider>();

            var umbrellaFund = new ReadUmbrellaFund { UmbrellaFundCode = UmbrellaFundCode };

            documentStorageMock.Setup(x => x.GetDocument<ReadUmbrellaFund>(It.IsAny<string>(), It.IsAny<string>())).Returns(new OperationResponse<ReadUmbrellaFund>
            {
                Success = true,
                Result = umbrellaFund
            });

            documentStorageProviderMock.Setup(x => x.GetDocumentStorage()).Returns(documentStorageMock.Object);

            var repository = new UmbrellaFundReadRepository(documentStorageProviderMock.Object);
            var response = repository.GetUmbrellaFund(UmbrellaFundCode);

            Assert.IsNotNull(response);
            Assert.AreEqual(response.UmbrellaFundCode, UmbrellaFundCode);
        }

        [TestMethod]
        public void UmbrellaFundReadRepository_GetUmbrellaFundList()
        {
            var documentStorageMock = new Mock<IDocumentStorage>();
            var documentStorageProviderMock = new Mock<IDocumentStorageProvider>();

            var umbrellaFund = new ReadUmbrellaFund { UmbrellaFundCode = UmbrellaFundCode };
            var umbrellaFundList = new List<ReadUmbrellaFund> { umbrellaFund };

            documentStorageMock.Setup(x => x.GetAllDocuments<ReadUmbrellaFund>(It.IsAny<string>())).Returns(new OperationResponse<IEnumerable<ReadUmbrellaFund>>
            {
                Success = true,
                Result = umbrellaFundList
            });

            documentStorageProviderMock.Setup(x => x.GetDocumentStorage()).Returns(documentStorageMock.Object);

            var repository = new UmbrellaFundReadRepository(documentStorageProviderMock.Object);
            var response = repository.GetUmbrellaFundList();

            Assert.IsNotNull(response);
            var responseUmbrellaFundList = response.ToArray();

            Assert.AreEqual(responseUmbrellaFundList.Length, 1);
            Assert.AreEqual(responseUmbrellaFundList[0].UmbrellaFundCode, UmbrellaFundCode);
        }
    }
}
{
  "version": "1.0.0-*",

  "testRunner": "mstest",

  "dependencies": {
    "dotnet-test-mstest": "1.1.2-preview",
    "Moq": "4.5.28",
    "Schroders.Test.Infrastructure": "1.0.0-1",
    "Schroders.UmbrellaFundService.Repository": "1.0.0-*",
    "Schroders.UmbrellaFundService.Handlers": "1.0.0-*"
  },

  "frameworks": {
    "net461": {}
  }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Schroders.Bus.Core;
using Schroders.Bus.Core.Contracts;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.UmbrellaFundService.Repository.Contracts;

namespace Schroders.UmbrellaFundService.Handlers.Tests
{
    [TestClass]
    public class SaveUmbrellaFundMessageHandlerTests
    {
        [TestMethod]
        public void SaveUmbrellaFundMessageHandler_CanHandleMessage_ReturnsTrue()
        {
            var saveUmbrellaFundMessageHandler = new SaveUmbrellaFundMessageHandler(null);

            var message = new BusMessage { TopicName = NServiceBusTopics.AddUmbrellaFund };
            var result = saveUmbrellaFundMessageHandler.CanHandleMessage(message);
            
            Assert.IsTrue(result);
        }

        [TestMethod]
        public void SaveUmbrellaFundMessageHandler_CanHandleMessage_ReturnsFalse()
        {
            var saveUmbrellaFundMessageHandler = new SaveUmbrellaFundMessageHandler(null);

            var busMessage = new BusMessage { TopicName = "Unknown" };
            var result = saveUmbrellaFundMessageHandler.CanHandleMessage(busMessage);

            Assert.IsFalse(result);
        }

        [TestMethod]
        public void SaveUmbrellaFundMessageHandler_HandleMessage_AddUmbrellaFund()
        {
            var busMessage = new BusMessage { TopicName = NServiceBusTopics.AddUmbrellaFund, Payload = new WriteUmbrellaFund { UmbrellaFundCode = "TestUmbrellaFundCode" } };
            var busMock = new Mock<IBus>();
            var busContext = new BusContext(busMock.Object);

            var writeRepositoryMock = new Mock<IUmbrellaFundWriteRepository>();
            var saveUmbrellaFundMessageHandler = new SaveUmbrellaFundMessageHandler(writeRepositoryMock.Object);
            saveUmbrellaFundMessageHandler.HandleMessage(busContext, busMessage);
            
            writeRepositoryMock.Verify(x => x.CreateUmbrellaFund(It.IsAny<WriteUmbrellaFund>()));

            busMock.Verify(x => x.Publish(It.IsAny<string>(), It.IsAny<BusEvent>()));
        }

        [TestMethod]
        public void SaveUmbrellaFundMessageHandler_HandleMessage_UpdateUmbrellaFund()
        {
            var busMessage = new BusMessage { TopicName = NServiceBusTopics.UpdateUmbrellaFund, Payload = new WriteUmbrellaFund { UmbrellaFundCode = "TestUmbrellaFundCode" } };
            var busMock = new Mock<IBus>();
            var busContext = new BusContext(busMock.Object);

            var writeRepositoryMock = new Mock<IUmbrellaFundWriteRepository>();
            var saveUmbrellaFundMessageHandler = new SaveUmbrellaFundMessageHandler(writeRepositoryMock.Object);
            saveUmbrellaFundMessageHandler.HandleMessage(busContext, busMessage);

            writeRepositoryMock.Verify(x => x.UpdateUmbrellaFund(It.IsAny<WriteUmbrellaFund>()));

            busMock.Verify(x => x.Publish(It.IsAny<string>(), It.IsAny<BusEvent>()));
        }
    }
}

{
  "version": "1.0.0-*",

  "testRunner": "mstest",

  "dependencies": {
    "dotnet-test-mstest": "1.1.2-preview",
    "Microsoft.Extensions.Logging.Console": "1.1.0",
    "Moq": "4.5.28",
    "MSTest.TestFramework": "1.0.6-preview",
    "Schroders.UmbrellaFundService.Commands": "1.0.0-*",
    "Schroders.Test.Infrastructure": "1.0.0-1"
  },

  "frameworks": {
    "net461": {}
  }
}

using System.Collections.Generic;
using Microsoft.Extensions.Primitives;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Schroders.UmbrellaFundService.Commands.Requests;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.UmbrellaFundService.Repository.Contracts;
using Schroders.Test.Infrastructure;

namespace Schroders.UmbrellaFundService.Commands.Tests
{
    [TestClass]
    public class GetUmbrellaFundListCommandTests : TestBase
    {
        [TestMethod]
        public void Execute_ShouldReturnItemList()
        {
            var umbrellaFund = new ReadUmbrellaFund()
            {
                UmbrellaFundCode = "UmbrellaFundCode_001",
                Name = "Schroders Test"
            };

            var repositoryResponse = new[] { umbrellaFund };

            var repositoryMock = new Mock<IUmbrellaFundReadRepository>();
            repositoryMock.Setup(x => x.GetUmbrellaFundList()).Returns(repositoryResponse);

            var command = new GetUmbrellaFundListCommand(repositoryMock.Object);

            var request = new GetUmbrellaFundListRequest();
            var context = new Dictionary<string, object> {{"AuthorizationHeader", new StringValues(string.Empty) }};
            var response = command.Execute(request, context);

            Assert.IsNotNull(response);
            Assert.AreEqual(response.UmbrellaFund[0].UmbrellaFundCode, umbrellaFund.UmbrellaFundCode);
            Assert.AreEqual(response.UmbrellaFund[0].Name, umbrellaFund.Name);
        }
    }
}

using System.Collections.Generic;
using Autofac;
using Microsoft.Extensions.Primitives;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Schroders.UmbrellaFundService.Commands.Requests;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.UmbrellaFundService.Repository.Contracts;
using Schroders.Test.Infrastructure;

namespace Schroders.UmbrellaFundService.Commands.Tests
{
    [TestClass]
    public class GetUmbrellaFundCommandTests : TestBase
    {
        [TestMethod]
        public void Execute_ShouldReturnUmbrellaFund()
        {
            const string UmbrellaFundCode = "UmbrellaFundCode1";

            var item = new ReadUmbrellaFund()
            {
                UmbrellaFundCode = UmbrellaFundCode,
                Name = "Schroders Test"
            };

            var repositoryResponse = item;

            var repositoryMock = new Mock<IUmbrellaFundReadRepository>();
            repositoryMock.Setup(x => x.GetUmbrellaFund(UmbrellaFundCode)).Returns(repositoryResponse);

            ScopeAction action = scope =>
            {
                var request = new GetUmbrellaFundRequest { Id = UmbrellaFundCode };

                var command = new GetUmbrellaFundCommand(repositoryMock.Object);

                var context = new Dictionary<string, object> { { "AuthorizationHeader", new StringValues(string.Empty) } };
                var response = command.Execute(request, context);

                Assert.IsNotNull(response);
                Assert.AreEqual(response.UmbrellaFund.UmbrellaFundCode, UmbrellaFundCode);
            };

            RunAction(action, builder =>
            {
                builder.RegisterInstance(repositoryMock.Object).As<IUmbrellaFundReadRepository>();

                builder.RegisterType<GetUmbrellaFundCommand>()
                    .AsImplementedInterfaces()
                    .AsSelf()
                    .PropertiesAutowired();
            });
        }
    }
}


{
  "version": "1.0.0-*",

  "dependencies": {
    "Schroders.UmbrellaFundService.DataContracts": "1.0.0-*",
    "Schroders.Storage.Core": "1.0.0-6"
  },

  "frameworks": {
    "net461": {
      "dependencies": {
      }
    }
  }
}
using Schroders.Storage.Core;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.UmbrellaFundService.Repository.Contracts;

namespace Schroders.UmbrellaFundService.Repository
{
    public class UmbrellaFundWriteRepository : IUmbrellaFundWriteRepository
    {
        private readonly IDocumentStorageProvider documentStorageProvider;

        public UmbrellaFundWriteRepository(IDocumentStorageProvider documentStorageProvider)
        {
            this.documentStorageProvider = documentStorageProvider;
        }

        public void CreateUmbrellaFund(WriteUmbrellaFund umbrellaFund)
        {
            this.documentStorageProvider.GetDocumentStorage().CreateDocument("UmbrellaFund", umbrellaFund.UmbrellaFundCode, umbrellaFund);
        }

        public void UpdateUmbrellaFund(WriteUmbrellaFund umbrellaFund)
        {
            this.documentStorageProvider.GetDocumentStorage().UpdateDocument("UmbrellaFund", umbrellaFund.UmbrellaFundCode, umbrellaFund);
        }
    }
}


using System.Collections.Generic;
using Schroders.Storage.Core;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.UmbrellaFundService.Repository.Contracts;

namespace Schroders.UmbrellaFundService.Repository
{
    public class UmbrellaFundReadRepository : IUmbrellaFundReadRepository
    {
        private readonly IDocumentStorageProvider documentStorageProvider;

        public UmbrellaFundReadRepository(IDocumentStorageProvider documentStorageProvider)
        {
            this.documentStorageProvider = documentStorageProvider;
        }

        public ReadUmbrellaFund GetUmbrellaFund(string id)
        {
            var response = documentStorageProvider.GetDocumentStorage().GetDocument<ReadUmbrellaFund>("UmbrellaFund", id);
            return response.Result;
        }

        public IEnumerable<ReadUmbrellaFund> GetUmbrellaFundList()
        {
            var response = documentStorageProvider.GetDocumentStorage().GetAllDocuments<ReadUmbrellaFund>("UmbrellaFund");
            return response.Result;
        }
    }
}

using System.Collections.Generic;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;

namespace Schroders.UmbrellaFundService.Repository.Contracts
{
    public interface IUmbrellaFundReadRepository
    {
        ReadUmbrellaFund GetUmbrellaFund(string id);

        IEnumerable<ReadUmbrellaFund> GetUmbrellaFundList();
    }
}


using Schroders.UmbrellaFundService.DataContracts.DomainModel;

namespace Schroders.UmbrellaFundService.Repository.Contracts
{
    public interface IUmbrellaFundWriteRepository
    {
        void CreateUmbrellaFund(WriteUmbrellaFund umbrellaFund);
        void UpdateUmbrellaFund(WriteUmbrellaFund umbrellaFund);
    }
}

{
  "version": "1.0.0-*",

  "dependencies": {
    "Schroders.UmbrellaFundService.DataContracts": "1.0.0-*",
    "Schroders.UmbrellaFundService.Repository": "1.0.0-*",
    "Schroders.Bus.Core": "1.0.0-6"
  },

  "frameworks": {
    "net461": {
      "dependencies": {
      }
    }
  }
}

using Schroders.Bus.Core;
using Schroders.Bus.Core.Contracts;
using Schroders.UmbrellaFundService.DataContracts.DomainModel;
using Schroders.UmbrellaFundService.Repository.Contracts;

namespace Schroders.UmbrellaFundService.Handlers
{
    public class SaveUmbrellaFundMessageHandler : IBusHandler
    {
        private readonly IUmbrellaFundWriteRepository writeRepository;

        public SaveUmbrellaFundMessageHandler(IUmbrellaFundWriteRepository writeRepository)
        {
            this.writeRepository = writeRepository;
        }

        public bool CanHandleMessage(BusMessage message)
        {
            return message?.TopicName == NServiceBusTopics.AddUmbrellaFund || message?.TopicName == NServiceBusTopics.UpdateUmbrellaFund;
        }

        public BusHandlerResponse HandleMessage(BusContext busContext, BusMessage busMessage)
        {
            var umbrellaFund = busMessage.Payload as WriteUmbrellaFund;
            if (string.IsNullOrEmpty(umbrellaFund?.UmbrellaFundCode))
            {
                return new BusHandlerResponse();
            }

            switch (busMessage.TopicName)
            {
                case NServiceBusTopics.AddUmbrellaFund:
                    this.writeRepository.CreateUmbrellaFund(umbrellaFund);
                    break;
                case NServiceBusTopics.UpdateUmbrellaFund:
                    this.writeRepository.UpdateUmbrellaFund(umbrellaFund);
                    break;
            }

            busContext.Bus.Publish(
                NServiceBusTopics.UmbrellaFundChanged,
                new BusEvent
                {
                    TopicName = NServiceBusTopics.UmbrellaFundChanged,
                    Payload = umbrellaFund.UmbrellaFundCode
                });

            return new BusHandlerResponse();
        }
    }
}

namespace Schroders.UmbrellaFundService.Handlers
{
    public class NServiceBusTopics
    {
        public const string AddUmbrellaFund = "AddUmbrellaFund";
        public const string UpdateUmbrellaFund = "UpdateUmbrellaFund";
        public const string UmbrellaFundChanged = "UmbrellaFundChanged";
    }
}

{
  "version": "1.0.0-*",

  "dependencies": {
    
  },

  "frameworks": {
    "net461": {
      "dependencies": {
      }
    }
  }
}


namespace Schroders.UmbrellaFundService.DataContracts.DomainModel
{
    public class WriteUmbrellaFund
    {
        public string UmbrellaFundCode { get; set; }

        public string PlatformUmbrellaCode { get; set; }

        public string PlatformSystemSourceCode { get; set; }

        public string ManagementCompanyCode { get; set; }

        public string Name { get; set; }

        public string CountryOfDomicile { get; set; }

        public string TypeOfVehicle { get; set; }
    }
}

namespace Schroders.UmbrellaFundService.DataContracts.DomainModel
{
    public class ReadUmbrellaFund
    {
        public string UmbrellaFundCode { get; set; }

        public string PlatformUmbrellaCode { get; set; }

        public string PlatformSystemSourceCode { get; set; }

        public string ManagementCompanyCode { get; set; }

        public string Name { get; set; }

        public string CountryOfDomicile { get; set; }

        public string TypeOfVehicle { get; set; }
    }
}
using System.Collections.Generic;

namespace Schroders.UmbrellaFundService.DataContracts.Configurations
{
    public class IdentityAuthenticationConfiguration
    {
        public string Authority { get; set; }

        public string ApiName { get; set; }

        public string ApiSecret { get; set; }

        public List<string> AllowedScopes { get; set; }

    }
}

{
  "version": "1.0.0-*",

  "dependencies": {
    "Schroders.Bus.Core": "1.0.0-6",
    "Schroders.UmbrellaFundService.DataContracts": "1.0.0-*",
    "Schroders.UmbrellaFundService.Repository": "1.0.0-*",
    "Schroders.ServiceBase.Commands": "1.0.0-2"
  },

  "frameworks": {
    "net461": {
      "dependencies": {
        "System.Net.Http": "4.1.1"
      }
    }
  }
}
using Microsoft.AspNetCore.Hosting;
using Schroders.ServiceBase.Hosting;

namespace Schroders.UmbrellaFundService
{
    public class UmbrellaFundService : HostableService
    {
        public UmbrellaFundService(HostingConfiguration config, string contentRoot) : base(config, contentRoot) 
        {
        }

        protected override IWebHost CreateHost(HostingConfiguration config, string contentRoot)
        {
            return new WebHostBuilder()
                .UseKestrel()
                .UseUrls(config.Urls)
                .UseContentRoot(contentRoot)
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NServiceBus;
using NServiceBus.Logging;
using NServiceBus.Serilog;
using Schroders.Bus.Core;
using Schroders.Bus.Core.Contracts;
using Schroders.Bus.NServiceBus.Extensions;
using Schroders.Bus.NServiceBus.Helpers;
using Schroders.Logging.Core.Middleware;
using Schroders.Logging.Serilog.Middleware;
using Schroders.ServiceBase.Commands;
using Schroders.ServiceBase.Commands.Pipeline;
using Schroders.ServiceBase.Commands.Pipeline.PipelineFactory;
using Schroders.ServiceBase.Commands.PipelineActions;
using Schroders.Storage.CouchbaseDocumentStorage.Extensions;
using Schroders.UmbrellaFundService.Commands;
using Schroders.UmbrellaFundService.Commands.Requests;
using Schroders.UmbrellaFundService.Commands.Responses;
using Schroders.UmbrellaFundService.DataContracts.Configurations;
using Schroders.UmbrellaFundService.Extensions;
using Schroders.UmbrellaFundService.Handlers;
using Schroders.UmbrellaFundService.Repository;
using Schroders.UmbrellaFundService.Repository.Contracts;
using Schroders.UmbrellaFundService.Swagger;
using Serilog;
using ILoggerFactory = Microsoft.Extensions.Logging.ILoggerFactory;

namespace Schroders.UmbrellaFundService
{
    using IdentityAuthenticationConfiguration = IdentityAuthenticationConfiguration;

    public class Startup
    {
        public const string CorsPolicyName = "default";

        public IContainer ApplicationContainer { get; private set; }

        public IConfigurationRoot Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            this.Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCors(
                options =>
                    {
                        options.AddPolicy(
                            CorsPolicyName,
                            policy => { policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); });
                    });

            var defaultPolicy =
                new AuthorizationPolicyBuilder().AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser().Build();

            services.AddAuthorization(opts => { opts.DefaultPolicy = defaultPolicy; });

            services.AddMvc(
                setup =>
                    {
                        setup.Filters.Add(new AuthorizeFilter(defaultPolicy));
                        setup.Filters.Add(new CorsAuthorizationFilterFactory(CorsPolicyName));
                    }).AddJsonOptions(jsonOpt => { jsonOpt.SerializerSettings.ApplyDefault(); });

            // Swagger services.
            services.AddSwaggerGen();
            services.ConfigureSwaggerGen(
                options => { options.OperationFilter<AuthorizationHeaderParameterOperationFilter>(); });

            services.AddNServiceBus();

            services.AddOptions();

            services.AddCouchbaseStorage(this.Configuration);

            // Create the container builder.
            var builder = new ContainerBuilder();

            builder.RegisterType<SaveUmbrellaFundMessageHandler>().As<IBusHandler>();

            // Register Interceptors (for all commands)
            builder.RegisterGeneric(typeof(GenerateIdPipelineAction<,>)).AsImplementedInterfaces();
            builder.RegisterGeneric(typeof(TracePipelineAction<,>)).AsImplementedInterfaces();

            // Register Commands
            builder.RegisterType<GetUmbrellaFundCommand>().As<ICommand<GetUmbrellaFundRequest, GetUmbrellaFundResponse>>();
            builder.RegisterType<GetUmbrellaFundListCommand>().As<ICommand<GetUmbrellaFundListRequest, GetUmbrellaFundListResponse>>();

            builder.RegisterGeneric(typeof(Pipeline<,,>)).As(typeof(IPipeline<,,>)).SingleInstance();
            builder.RegisterType<PipelineFactory>().As<IPipelineFactory>().SingleInstance();

            builder.RegisterType<UmbrellaFundReadRepository>().As<IUmbrellaFundReadRepository>();
            builder.RegisterType<UmbrellaFundWriteRepository>().As<IUmbrellaFundWriteRepository>();

            builder.Populate(services);
            this.ApplicationContainer = builder.Build();

            LogManager.Use<SerilogFactory>();

            NServiceBusEndpointHosting.StartConfiguredEndpoints(
                this.Configuration,
                this.ApplicationContainer,
                new Dictionary<string, string[]>
                    {
                        {
                            "Schroders.UmbrellaFundService.Commands", new[] { NServiceBusTopics.AddUmbrellaFund, NServiceBusTopics.UpdateUmbrellaFund }
                        },
                        {
                            "Schroders.UmbrellaFundService.Publisher", new[] { NServiceBusTopics.UmbrellaFundChanged }
                        }
                    },
                allEndpointConfiguration =>
                    {
                        var directoryToScan = AppDomain.CurrentDomain.BaseDirectory;
                        var localFiles = Directory.GetFiles(directoryToScan);
                        var filteredFiles = localFiles.Select(Path.GetFileName).Where(fn => fn != "NServiceBus.Core.dll");

                        allEndpointConfiguration.ExcludeAssemblies(filteredFiles.ToArray());

                        allEndpointConfiguration.Conventions().DefiningMessagesAs(t => t == typeof(BusMessage));
                        allEndpointConfiguration.Conventions().DefiningCommandsAs(t => t == typeof(BusMessage));
                        allEndpointConfiguration.Conventions().DefiningEventsAs(t => t == typeof(BusEvent));
                    },
                new Dictionary<string, Action<EndpointConfiguration>>
                    {
                        {
                            "Schroders.UmbrellaFundService.Commands", ep => { }
                        },
                        {
                            "Schroders.UmbrellaFundService.Publisher", ep =>
                                {
                                    var transport = ep.UseTransport<MsmqTransport>();
                                    var routing = transport.Routing();
                                    routing.RouteToEndpoint(typeof(BusEvent), "Schroders.UmbrellaFundService.Events");
                                }
                        }
                    });

            return new AutofacServiceProvider(this.ApplicationContainer);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseMiddleware<SchrodersLoggingMiddleware>();
            app.UseMiddleware<SchrodersLoggingEnrichMiddleware>();

            loggerFactory.AddSerilog();
            var @switch = new SourceSwitch("TraceSwitch")
            {
                Level = SourceLevels.Verbose
            };
            loggerFactory.AddTraceSource(@switch, new TextWriterTraceListener(writer: Console.Out));

            app.UseCors(CorsPolicyName);

            var section = this.Configuration.GetSection(nameof(IdentityAuthenticationConfiguration));
            var authenticationConfiguration = new IdentityAuthenticationConfiguration();
            section.Bind(authenticationConfiguration);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = authenticationConfiguration.Authority,
                RequireHttpsMetadata = false,
                EnableCaching = false,
                ApiName = authenticationConfiguration.ApiName,
                ApiSecret = authenticationConfiguration.ApiSecret,
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                ValidateScope = true,
                RoleClaimType = "product_master_roles",
                AllowedScopes = authenticationConfiguration.AllowedScopes
            });

            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUi();
        }
    }
}


{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "System": "Information",
        "Microsoft": "Information"
      }
    },
    "WriteTo": [
      { "Name": "LiterateConsole" },
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "logs\\UmbrellaFundService-{Date}.log",
          "retainedFileCountLimit": 3,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {TraceId} {TraceSpanId} {ApplicationName} {ApplicationVersion} {ApplicationInstanceId} {MachineName} {ProductName} {Message}{NewLine}{Exception}"
        }
      }
    ]
  }
}


{
  "dependencies": {
    "Autofac": "4.2.1",
    "Autofac.Extensions.DependencyInjection": "4.0.0",
    "IdentityServer4.AccessTokenValidation": "1.0.2",
    "Microsoft.AspNetCore.Mvc": "1.1.0",
    "Microsoft.AspNetCore.Routing": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0",
    "Microsoft.Extensions.Logging": "1.1.0",
    "Microsoft.Extensions.Logging.Console": "1.1.0",
    "Microsoft.Extensions.Logging.Debug": "1.1.0",
    "Microsoft.Extensions.Logging.TraceSource": "1.1.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
    "NServiceBus": "6.0.0",
    "NServiceBus.Autofac": "6.0.0",
    "NServiceBus.Serilog": "3.0.1",
    "Schroders.Bus.Core": "1.0.0-6",
    "Schroders.Bus.NServiceBus": "1.0.0-4",
    "Schroders.ServiceBase.Hosting": "1.0.0-1",
    "Schroders.Storage.Core": "1.0.0-6",
    "Schroders.Storage.CouchbaseStorage": "1.0.0-9",
    "Schroders.Storage.MemoryDocumentStorage": "1.0.0-4",
    "Schroders.UmbrellaFundService.Commands": "1.0.0-*",
    "Schroders.UmbrellaFundService.DataContracts": "1.0.0-*",
    "Schroders.UmbrellaFundService.Handlers": "1.0.0-*",
    "Serilog": "2.3.0",
    "Serilog.Enrichers.Environment": "2.1.1",
    "Serilog.Extensions.Logging": "1.3.1",
    "Serilog.Settings.Configuration": "2.2.0",
    "Serilog.Sinks.Literate": "2.0.0",
    "Serilog.Sinks.RollingFile": "3.2.0",
    "Swashbuckle": "6.0.0-beta902",
    "System.Linq": "4.0.0",
    "System.Net.Http": "4.0.0",
    "TopShelf.Serilog": "4.0.3",
    "Schroders.Logging.Core": "1.0.0-6",
    "Schroders.Logging.Serilog": "1.0.0-9",
    "Schroders.ServiceBase.Commands.Serilog": "1.0.0-10"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
    "Microsoft.DotNet.Watcher.Tools": "1.1.0-preview4-final"
  },

  "frameworks": {
    "net461": {}
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": false,
    "copyToOutput": {
      "includeFiles": [
        "appsettings.json",
        "hosting.json",
        "serilog.json"
      ]
    }
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "runtimes": {
    "win7-x64": {}
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "hosting.json",
      "serilog.json",
      "web.config",
      "NServiceBusHandlers/License.xml"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}
using System;
using Microsoft.Extensions.Configuration;
using Schroders.Logging.Serilog.Extensions;
using Schroders.ServiceBase.Hosting;
using Serilog;
using Topshelf.Logging;

namespace Schroders.UmbrellaFundService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var contentRoot = AppDomain.CurrentDomain.BaseDirectory;

            var config = new ConfigurationBuilder()
                .SetBasePath(contentRoot)
                .AddJsonFile("hosting.json", optional: false)
                .AddJsonFile("serilog.json", optional: false)
                .Build();

            var hostingConfiguration = config.Get<HostingConfiguration>();

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                .Enrich.FromLogContext()
                .Enrich.WithMachineName()
                .Enrich.WithSchrodersSettings(hostingConfiguration.ApplicationName)
                .CreateLogger();

            HostLogger.UseLogger(new SerilogLogWriterFactory.SerilogHostLoggerConfigurator(Log.Logger));

            HostingFacade.Run(() => new UmbrellaFundService(hostingConfiguration, contentRoot));
        }
    }
}

{
  "applicationName": "Schroders.UmbrellaFundService-Develop",
  "urls": "http://0.0.0.0:5007"
}

{
  "IdentityAuthenticationConfiguration": {
    "Authority": "http://localhost:5005",
    "AllowedScopes": [
      "UmbrellaFund"
    ]
  },

  "NServiceBusConfiguration": {
    "Endpoints": [
      {
        "Name": "Schroders.UmbrellaFundService.Commands",
        "FailedMessagesQueueName": "Schroders.UmbrellaFundService.FailedMessages"
      },
      {
        "Name": "Schroders.UmbrellaFundService.Publisher",
        "FailedMessagesQueueName": "Schroders.UmbrellaFundService.FailedMessages"
      }
    ]
  },

  "CouchbaseStorageConfiguration": {
    "ServerUrl": [
      "http://cblninvdev1.london.schroders.com:8091",
      "http://cblninvdev2.london.schroders.com:8091",
      "http://cblninvdev3.london.schroders.com:8091",
      "http://cblninvdev4.london.schroders.com:8091"
    ],
    "BucketName": "ProductMaster"
  },

  "ServiceDiscoveryConfiguration": {
    "ServiceUrl": "http://localhost:5000/service-discovery"
  }
}
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Authorization;
using Swashbuckle.Swagger.Model;
using Swashbuckle.SwaggerGen.Generator;

namespace Schroders.UmbrellaFundService.Swagger
{
    public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
            var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
            var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);

            if (isAuthorized && !allowAnonymous)
            {
                if (operation.Parameters == null)
                    operation.Parameters = new List<IParameter>();

                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "Authorization",
                    In = "header",
                    Description = "access token",
                    Required = true,
                    Type = "string",
                });
            }
        }
    }
}

using Schroders.Bus.Core;
using Schroders.Bus.Core.Contracts;
using Schroders.Bus.NServiceBus;

namespace Schroders.UmbrellaFundService.NServiceBusHandlers
{
    /// <summary>
    /// General NServiceBus handler for mapping BusMessage to specific NServiceBus messages and back
    /// It also executes appropriate topic hander 
    /// </summary>
    public class NServiceBusMessageHandler : BaseNServiceBusHandler<BusMessage>
    {
        public NServiceBusMessageHandler(IBusHandlerProvider busHandlerProvider, IBus bus)
            : base(
                busHandlerProvider, 
                bus, 
                nbusMessage => nbusMessage, 
                message => message)
        {
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<license id="7861e913-8f14-4d8a-a672-611506127506" expiration="2018-02-03T00:00:00.0000000" type="Standard" LicenseVersion="6.0" WorkerThreads="Max" AllowedNumberOfWorkerNodes="Max" MaxMessageThroughputPerSecond="Max" Quantity="9" Edition="Advanced" Applications="NServiceBus;ServiceControl;ServicePulse;">
  <name>Schroder Investment Management Ltd.</name>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
      <Reference URI="">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
        <DigestValue>kHMkHSbl1n1YYQlZ7W0uVygezos=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>HNbICxxco+U2imQKXLGMB4LNXqyFNZzCgm05b+3o0VO1jjnIj8LasR9+iCzbIIoV0yphcwwSgjbWKcH7ojVBBNzFx0g1VfW71tg4tEStIQHRjsaslRoPa+yl5FmYnOXbVin1C/2LkNpY5IQVOaqSsoAIlf162wLLkymZBEjnJaw=</SignatureValue>
  </Signature>
</license>

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace Schroders.UmbrellaFundService.Extensions
{
    public static class JsonSerializerSettingsExtensions
    {
        public static void ApplyDefault(this JsonSerializerSettings settings)
        {
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver { NamingStrategy = new CamelCaseNamingStrategy { ProcessDictionaryKeys = false } };
            settings.DefaultValueHandling = DefaultValueHandling.Ignore;
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            settings.Converters.Add(new StringEnumConverter());
        }
    }
}
using Schroders.Logging.Core.Extensions;
using Schroders.ServiceBase.Commands.PipelineActions;

namespace Schroders.UmbrellaFundService.Extensions
{
    public static class HttpContextExtractorExtensions
    {
        public static HttpContextExtractor ExtractRequiredContext(this HttpContextExtractor extractor)
        {
            extractor.Add("AuthorizationHeader", extractor.RequestContext.Request.Headers["Authorization"]);
            extractor.Add(GenerateIdPipelineActionBase.GenerateIdPipelineActionContextId, extractor.RequestContext.TraceIdentifier);

            return extractor;
        }
    }
}

using Microsoft.AspNetCore.Http;
using Schroders.Logging.Core.Extensions;

namespace Schroders.UmbrellaFundService.Extensions
{
    public static class HttpContextExtensions
    {
        public static HttpContextExtractor Extract(this HttpContext context)
        {
            return new HttpContextExtractor(context);
        }
    }
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Schroders.Logging.Core.Extensions;
using Schroders.ServiceBase.Commands.Pipeline;
using Schroders.ServiceBase.Commands.Pipeline.PipelineFactory;
using Schroders.UmbrellaFundService.Commands.Requests;
using Schroders.UmbrellaFundService.Commands.Responses;
using Schroders.UmbrellaFundService.Extensions;

namespace Schroders.UmbrellaFundService.Controllers
{
    [Authorize(Roles = "Admin, Operator, Readonly")]
    [Route("umbrellaFund")]
    public class UmbrellaFundController : Controller
    {
        private readonly IPipelineFactory pipelineFactory;

        private readonly ILogger<UmbrellaFundController> logger;

        public UmbrellaFundController(IPipelineFactory pipelineFactory, ILogger<UmbrellaFundController> logger)
        {
            this.logger = logger;
            this.pipelineFactory = pipelineFactory;
        }

        [HttpGet]
        [ProducesResponseType(typeof(GetUmbrellaFundListResponse), 200)]
        [ProducesResponseType(typeof(ErrorResult), 500)]
        public IActionResult GetAll()
        {
            var request = new GetUmbrellaFundListRequest();
            var requestContext = HttpContext.Extract()
                .ExtractRequiredContext()
                .ExtractLoggingContext();

            var result = this.pipelineFactory.Get<GetUmbrellaFundListRequest, GetUmbrellaFundListResponse>().Execute(request, requestContext);
            if (result.Success)
            {
                return this.Ok(result.Result);
            }

            return this.StatusCode(500, result.Error);
        }

        [HttpGet("{id}")]
        [ProducesResponseType(typeof(GetUmbrellaFundResponse), 200)]
        [ProducesResponseType(typeof(ErrorResult), 500)]
        public IActionResult Get(string id)
        {
            var request = new GetUmbrellaFundRequest { Id = id };
            var requestContext = HttpContext.Extract()
                .ExtractRequiredContext()
                .ExtractLoggingContext();

            var result = this.pipelineFactory.Get<GetUmbrellaFundRequest, GetUmbrellaFundResponse>().Execute(request, requestContext);
            if (result.Success)
            {
                return this.Ok(result.Result);
            }

            return this.StatusCode(500, result.Error);
        }
    }
}


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <clear/>
    <add key="Schroders" value="\\lux0201.lux.schroders.com\Nuget\Schroders" />
    <add key="Externals" value="http://proget.schroders.com/nuget/PublicNuGetRepo" />
    <add key="NuGet official package source" value="https://nuget.org/api/v2/" />
  </packageSources>
</configuration>
{
  "projects": [ "src", "samples" ],
  "sdk": {
    "version": "1.0.0-preview2-1-003177"
  }
}

Comments