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-LWWeyo */
{
  "version": "1.0.0-*",

  "dependencies": {
    "Schroders.Bus.Core": "1.0.0-6",
    "ProductMaster.FundShareClass.DataContracts": "1.0.0-*",
    "ProductMaster.FundShareClass.Repository": "1.0.0-*",
    "Schroders.ServiceBase.Commands": "1.0.0-2",
    "Newtonsoft.Json": "9.0.1"
  },

  "frameworks": {
    "net461": {
      "dependencies": {
        "System.Net.Http": "4.1.1"
      }
    }
  }
}


namespace ProductMaster.FundShareClass.Commands
{
    using DataContracts.Requests;
    using DataContracts.Responses;
    using Repository;
    using Schroders.ServiceBase.Commands;
    using System.Collections.Generic;
    using System.Linq;

    public class GetShareClassListCommand : ICommand<GetShareClassListRequest, GetShareClassListResponse>
    {
        private readonly IShareClassReadRespository readRepository;

        public GetShareClassListCommand(IShareClassReadRespository readRepository)
        {
            this.readRepository = readRepository;
        }

        public GetShareClassListResponse Execute(GetShareClassListRequest request, IDictionary<string, object> context)
        {
            var shareClasses = this.readRepository.GetShareClasses().ToList();
            return new GetShareClassListResponse { ShareClasses = shareClasses };
        }
    }
}

namespace ProductMaster.FundShareClass.Commands
{
    using DataContracts.Requests;
    using DataContracts.Responses;
    using Repository;
    using Schroders.ServiceBase.Commands;
    using System.Collections.Generic;

    public class GetShareClassCommand : ICommand<GetShareClassRequest, GetShareClassResponse>
    {
        private readonly IShareClassReadRespository shareClassRepository;

        public GetShareClassCommand(IShareClassReadRespository shareClassRepository)
        {
            this.shareClassRepository = shareClassRepository;
        }

        public GetShareClassResponse Execute(GetShareClassRequest request, IDictionary<string, object> context)
        {
            var shareClass = this.shareClassRepository.GetShareClass(request.Id);
            return new GetShareClassResponse { ShareClass = shareClass };
        }
    }
}
{
  "version": "1.0.0-*",

  "dependencies": {
    "Autofac": "4.2.1",
    "Autofac.Extensions.DependencyInjection": "4.0.0",
    "IdentityServer4.AccessTokenValidation": "1.0.1-rc4-update1",
    "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",
    "ProductMaster.FundShareClass.Commands": "1.0.0-*",
    "ProductMaster.FundShareClass.Common": "1.0.0-*",
    "ProductMaster.FundShareClass.DataContracts": "1.0.0-*",
    "ProductMaster.FundShareClass.Handlers": "1.0.0-*",
    "Schroders.Bus.Core": "1.0.0-6",
    "Schroders.Bus.NServiceBus": "1.0.0-4",
    "Schroders.Logging.Serilog": "1.0.0-9",
    "Schroders.ServiceBase.Commands.Serilog": "1.0.0-9",
    "Schroders.ServiceBase.Hosting": "1.0.0-1",
    "Schroders.Storage.Core": "1.0.0-2",
    "Schroders.Storage.CouchbaseStorage": "1.0.0-4",
    "Schroders.Storage.MemoryDocumentStorage": "1.0.0-2",
    "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"
  },

  "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",
      "web.config"    
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

namespace ProductMaster.FundShareClass
{
    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using Commands;
    using Common;
    using DataContracts.Requests;
    using DataContracts.Responses;
    using Extensions;
    using Handlers;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc.Cors.Internal;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyModel;
    using Microsoft.Extensions.Logging;
    using NServiceBus;
    using NServiceBus.Logging;
    using NServiceBus.Serilog;
    using ProductService.Swagger;
    using Repository;
    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.ServiceBase.Commands.Serilog.PipelineActions;
    using Schroders.Storage.CouchbaseDocumentStorage.Extensions;
    using Serilog;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    using ILoggerFactory = Microsoft.Extensions.Logging.ILoggerFactory;

    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();

            // Workaround for mstest application domain
            var assembly = Assembly.GetEntryAssembly();
            var dependencyContext = (assembly == null)
                                        ? DependencyContext.Load(this.GetType().Assembly)
                                        : DependencyContext.Default;          
        }

        // 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<AddUpdateShareClassHandler>().As<IBusHandler>();
            builder.RegisterType<RemoveShareClassMessageHandler>().As<IBusHandler>();

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

            // Register Commands
            builder.RegisterType<GetShareClassCommand>().As<ICommand<GetShareClassRequest, GetShareClassResponse>>();
            builder.RegisterType<GetShareClassListCommand>().As<ICommand<GetShareClassListRequest, GetShareClassListResponse>>();

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

            builder.RegisterType<ShareClassReadRepository>().As<IShareClassReadRespository>();
            builder.RegisterType<ShareClassWriteRepository>().As<IShareClassWriteRepository>();

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

            LogManager.Use<SerilogFactory>();

            NServiceBusEndpointHosting.StartConfiguredEndpoints(
                this.Configuration,
                this.ApplicationContainer,
                new Dictionary<string, string[]>
                    {
                        {
                            "ProductMaster.FundShareClass.Commands", new[] { ShareClassNames.AddUpdateShareClass,  ShareClassNames.RemoveShareClass, ShareClassNames.ShareClassChanged }
                        },
                         {
                            "ProductMaster.FundShareClass.Publisher", new[]
                                                                    {
                                                                        "ShareClassCreated"
                                                                    }
                        }
                    },
                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());
                },
                new Dictionary<string, Action<EndpointConfiguration>>
                    {
                        {
                            "ProductMaster.FundShareClass.Commands", ep =>
                                {
                                    ep.Conventions().DefiningMessagesAs(t => t == typeof(BusMessage));
                                    ep.Conventions().DefiningCommandsAs(t => t == typeof(BusMessage));
                                    ep.Conventions().DefiningEventsAs(t => t == typeof(BusEvent));
                                }
                        },
                        {
                            "ProductMaster.FundShareClass.Publisher", ep =>
                            {
                                  ep.Conventions().DefiningMessagesAs(t => t == typeof(BusMessage));
                                  ep.Conventions().DefiningEventsAs(t => t == typeof(BusEvent));
                            }
                        }
                    });

            return new AutofacServiceProvider(this.ApplicationContainer);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddSerilog();

            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,
            //    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\\FundshareClass-{Date}.log",
          "retainedFileCountLimit": 3,
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {TraceId} {TraceLegId} {ApplicationName} {ApplicationVersion} {ApplicationInstanceId} {MachineName} {ProductName} {Message}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ]
  }
}
namespace ProductMaster.FundShareClass
{
    using System;
    using Microsoft.Extensions.Configuration;
    using Schroders.Logging.Serilog.Extensions;
    using Schroders.ServiceBase.Hosting;
    using Serilog;
    using Topshelf.Logging;
    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 FundShareClassService(hostingConfiguration, contentRoot));
        }
    }

{
  "applicationName": "ProductMaster.FundShareClass-Develop",
  "urls": "http://0.0.0.0:5040"
}

namespace ProductMaster.FundShareClass.Controllers
{
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System.Linq;

    using Schroders.Logging.Core.Extensions;
    using Schroders.ServiceBase.Commands.Pipeline;
    using Schroders.ServiceBase.Commands.Pipeline.PipelineFactory;
    using DataContracts.Responses;
    using DataContracts.Requests;
    using Extensions;

    [Route("shareclasses")]
    public class ShareClassController : Controller
    {
        private readonly IPipelineFactory pipelineFactory;

        private readonly ILogger<ShareClassController> logger;

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

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

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

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

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

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

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


}

Comments