Commit 39a3424d by martin.slowinski

Initial Commit

parents
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
logs
ecommerce_logs
/health_check_logs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit https://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<!--
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
-->
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<!--
In the example below, the "Replace" transform will replace the entire
<customErrors> section of your web.config file.
Note that because there is only one customErrors section under the
<system.web> node, there is no need to use the "xdt:Locator" attribute.
<customErrors defaultRedirect="GenericError.htm"
mode="RemoteOnly" xdt:Transform="Replace">
<error statusCode="500" redirect="InternalError.htm"/>
</customErrors>
-->
</system.web>
</configuration>
\ No newline at end of file
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
\ No newline at end of file
using System;
using System.Threading.Tasks;
using SoapConsumer.Infrastructure.CQRS.Commands.Generic;
using SoapConsumer.Infrastructure.CQRS.Events;
using SoapConsumer.Infrastructure.CQRS.Events.Generic;
namespace SoapConsumer.Infrastructure.CQRS.Commands
{
public class CommandBus : ICommandBus
{
private readonly Func<Type, IHandleCommand> _handlersFactory;
private readonly IEventBus _eventBus;
public CommandBus(Func<Type, IHandleCommand> handlersFactory, IEventBus eventBus)
{
_handlersFactory = handlersFactory;
_eventBus = eventBus;
}
public async Task SendAsync<TCommand>(TCommand command)
where TCommand : ICommand
{
var commandBeforeEvent = new BeforeCommandExecutionEvent<TCommand> { Command = command };
await _eventBus.PublishAsync(commandBeforeEvent);
if (commandBeforeEvent.Abort)
{
return;
}
var handler = (IHandleCommand<TCommand>)this._handlersFactory(typeof(TCommand));
if (handler == null)
{
throw new InvalidOperationException($"Handler for {typeof(TCommand)} probably was not defined.");
}
await handler.ExecuteAsync(command);
var commandAfterEvent = new AfterCommandExecutionEvent<TCommand> { Command = command };
await _eventBus.PublishAsync(commandAfterEvent);
}
}
}
\ No newline at end of file
using System.Threading.Tasks;
namespace SoapConsumer.Infrastructure.CQRS.Commands.Generic
{
public interface IHandleCommand<in TCommand> : IHandleCommand
where TCommand : ICommand
{
Task ExecuteAsync(TCommand command);
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Commands
{
public interface ICommand
{
}
}
\ No newline at end of file
using System.Threading.Tasks;
namespace SoapConsumer.Infrastructure.CQRS.Commands
{
public interface ICommandBus
{
Task SendAsync<TCommand>(TCommand command) where TCommand : ICommand;
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Commands
{
public interface IHandleCommand
{
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SoapConsumer.Infrastructure.CQRS.Events.Generic;
namespace SoapConsumer.Infrastructure.CQRS.Events
{
public class EventBus : IEventBus
{
private readonly Func<Type, IEnumerable<IHandleEvent>> _handlersFactory;
public EventBus(Func<Type, IEnumerable<IHandleEvent>> handlersFactory)
{
_handlersFactory = handlersFactory;
}
public async Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent
{
var handlers = _handlersFactory(typeof(TEvent)).Cast<IHandleEvent<TEvent>>();
foreach (IHandleEvent<TEvent> handler in handlers)
{
await handler.HandleAsync(@event);
}
}
}
}
\ No newline at end of file
using SoapConsumer.Infrastructure.CQRS.Commands;
namespace SoapConsumer.Infrastructure.CQRS.Events.Generic
{
public class AfterCommandExecutionEvent<TCommand> : IEvent
where TCommand : ICommand
{
public TCommand Command { get; set; }
}
}
\ No newline at end of file
using SoapConsumer.Infrastructure.CQRS.Queries;
namespace SoapConsumer.Infrastructure.CQRS.Events.Generic
{
public class AfterQueryExecutionEvent<TQuery> : IEvent
where TQuery : IQuery
{
public TQuery Query { get; set; }
public object Result { get; set; }
}
}
\ No newline at end of file
using SoapConsumer.Infrastructure.CQRS.Commands;
namespace SoapConsumer.Infrastructure.CQRS.Events.Generic
{
public class BeforeCommandExecutionEvent<TCommand> : IEvent
where TCommand : ICommand
{
public bool Abort { get; set; }
public TCommand Command { get; set; }
}
}
\ No newline at end of file
using SoapConsumer.Infrastructure.CQRS.Queries;
namespace SoapConsumer.Infrastructure.CQRS.Events.Generic
{
public class BeforeQueryExecutionEvent<TQuery> : IEvent
where TQuery : IQuery
{
public bool Abort { get; set; }
public TQuery Query { get; set; }
}
}
\ No newline at end of file
using System.Threading.Tasks;
namespace SoapConsumer.Infrastructure.CQRS.Events.Generic
{
public interface IHandleEvent<in TEvent> : IHandleEvent
where TEvent : IEvent
{
Task HandleAsync(TEvent @event);
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Events
{
public interface IEvent
{
}
}
\ No newline at end of file
using System.Threading.Tasks;
namespace SoapConsumer.Infrastructure.CQRS.Events
{
public interface IEventBus
{
Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent;
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Events
{
public interface IHandleEvent
{
}
}
\ No newline at end of file
using System.Threading.Tasks;
namespace SoapConsumer.Infrastructure.CQRS.Queries.Generic
{
public interface IHandleQuery<in TQuery, TResult> : IHandleQuery
where TQuery : IQuery<TResult>
{
Task<TResult> HandleAsync(TQuery query);
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Queries.Generic
{
public interface IPagedQuery<TResult> : IQuery<TResult>
{
int PageNumber { get; set; }
int PageSize { get; set; }
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Queries.Generic
{
public interface IQuery<TResult> : IQuery
{
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Queries
{
public interface IHandleQuery
{
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Queries
{
public interface IPagedQuery : IQuery
{
int PageNumber { get; set; }
int PageSize { get; set; }
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.CQRS.Queries
{
public interface IQuery
{
}
}
\ No newline at end of file
using System.Threading.Tasks;
using SoapConsumer.Infrastructure.CQRS.Queries.Generic;
namespace SoapConsumer.Infrastructure.CQRS.Queries
{
public interface IQueryBus
{
Task<TResult> ExecuteAsync<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>;
}
}
\ No newline at end of file
using System;
using System.Threading.Tasks;
using SoapConsumer.Infrastructure.CQRS.Events;
using SoapConsumer.Infrastructure.CQRS.Events.Generic;
using SoapConsumer.Infrastructure.CQRS.Queries.Generic;
namespace SoapConsumer.Infrastructure.CQRS.Queries
{
public class QueryBus : IQueryBus
{
private readonly Func<Type, IHandleQuery> _handlersFactory;
private readonly IEventBus _eventBus;
public QueryBus(Func<Type, IHandleQuery> handlersFactorycontext, IEventBus eventBus)
{
_handlersFactory = handlersFactorycontext;
_eventBus = eventBus;
}
public async Task<TResult> ExecuteAsync<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>
{
var beforeQueryEvent = new BeforeQueryExecutionEvent<TQuery> { Query = query };
await _eventBus.PublishAsync(beforeQueryEvent);
if (beforeQueryEvent.Abort)
{
return default;
}
var handler = (IHandleQuery<TQuery, TResult>)this._handlersFactory(typeof(TQuery));
var result = handler != null ? await handler.HandleAsync(query) : default(TResult);
var afterQueryEvent = new AfterQueryExecutionEvent<TQuery> { Query = query, Result = result };
await _eventBus.PublishAsync(afterQueryEvent);
return result;
}
}
}
\ No newline at end of file
using System;
using Microsoft.Extensions.Configuration;
namespace SoapConsumer.Infrastructure.Helpers
{
public static class ConfigurationSectionExtensions
{
public static string GetValue(this IConfigurationSection configurationSection)
{
var isValid = !string.IsNullOrEmpty(configurationSection.Value);
if (!isValid)
{
throw new InvalidOperationException($"Value for patch: {configurationSection.Path} in settings does not exist or is empty");
}
return configurationSection.Value;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using SoapConsumer.Infrastructure.CQRS.Commands;
using SoapConsumer.Infrastructure.CQRS.Commands.Generic;
using SoapConsumer.Infrastructure.CQRS.Events;
using SoapConsumer.Infrastructure.CQRS.Events.Generic;
using SoapConsumer.Infrastructure.CQRS.Queries;
using SoapConsumer.Infrastructure.CQRS.Queries.Generic;
namespace SoapConsumer.Infrastructure.Modules
{
public class CQRSModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
RegisterEventsBus(builder);
RegisterCommandBus(builder);
RegisterQueryBus(builder);
}
public void RegisterCommandBus(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterAssemblyTypes(ThisAssembly)
.Where(x => x.IsAssignableTo<IHandleCommand>())
.AsImplementedInterfaces();
builder.Register<Func<Type, IHandleCommand>>(c =>
{
var ctx = c.Resolve<IComponentContext>();
return t =>
{
var handlerType = typeof(IHandleCommand<>).MakeGenericType(t);
return (IHandleCommand)ctx.Resolve(handlerType);
};
});
builder.RegisterType<CommandBus>().AsImplementedInterfaces();
}
protected void RegisterEventsBus(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(ThisAssembly)
.Where(x => x.IsAssignableTo<IHandleEvent>())
.AsImplementedInterfaces();
builder.Register<Func<Type, IEnumerable<IHandleEvent>>>(c =>
{
var ctx = c.Resolve<IComponentContext>();
return t =>
{
var handlerType = typeof(IHandleEvent<>).MakeGenericType(t);
var handlersCollectionType = typeof(IEnumerable<>).MakeGenericType(handlerType);
return (IEnumerable<IHandleEvent>)ctx.Resolve(handlersCollectionType);
};
});
builder.RegisterType<EventBus>().AsImplementedInterfaces();
}
public void RegisterQueryBus(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterAssemblyTypes(ThisAssembly)
.Where(x => x.IsAssignableTo<IHandleQuery>())
.AsImplementedInterfaces();
builder.Register<Func<Type, IHandleQuery>>(c =>
{
var ctx = c.Resolve<IComponentContext>();
return t =>
{
var queryInterfaceType = t.GetInterfaces().First(i => typeof(IQuery).IsAssignableFrom(i));
var handlerType = typeof(IHandleQuery<,>).MakeGenericType(t, queryInterfaceType.GenericTypeArguments.FirstOrDefault());
return (IHandleQuery)ctx.Resolve(handlerType);
};
});
builder.RegisterType<QueryBus>().AsImplementedInterfaces();
}
}
}
\ No newline at end of file
using Autofac;
using SoapConsumer.Infrastructure.Transformers;
namespace SoapConsumer.Infrastructure.Modules
{
public class TransformersModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<PipelineTransformer>().AsImplementedInterfaces();
}
}
}
using Autofac;
using SoapConsumer.Infrastructure.Proxy;
using SoapConsumer.Infrastructure.Proxy.Builders;
namespace SoapConsumer.Infrastructure.Modules
{
public class WebServiceProxyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<WebServiceProxy>().AsImplementedInterfaces();
builder.RegisterType<SoapXmlBuilder>().AsImplementedInterfaces();
}
}
}
using System.Threading.Tasks;
namespace SoapConsumer.Infrastructure.Proxy.Abstract
{
public interface IWebServiceProxy
{
Task<TModel> ExecuteAsync<TModel, TParams>(TParams parameters);
}
}
\ No newline at end of file
using System;
namespace SoapConsumer.Infrastructure.Proxy.Attributes
{
[AttributeUsage(AttributeTargets.Class)]
public class SoapAttribute : Attribute
{
public string Endpoint { get; set; }
public string Operation { get; set; }
public string Namespace { get; set; }
public string Host { get; set; }
}
}
\ No newline at end of file
namespace SoapConsumer.Infrastructure.Proxy.Builders.Abstract
{
public interface ISoapXmlBuilder
{
string Build<T>(T value, string @namespace);
}
}
\ No newline at end of file
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using SoapConsumer.Infrastructure.Proxy.Builders.Abstract;
namespace SoapConsumer.Infrastructure.Proxy.Builders
{
public class SoapXmlBuilder : ISoapXmlBuilder
{
public string Build<T>(T value, string @namespace)
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("", @namespace);
var serializer = new XmlSerializer(value.GetType(), @namespace);
var settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (var stream = new StringWriter())
{
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, namespaces);
}
var xmlRoot = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap12:Envelope
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
<soap12:Body>
{stream.ToString()}
</soap12:Body >
</soap12:Envelope > ";
return xmlRoot;
}
}
}
}
\ No newline at end of file
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Configuration;
using SoapConsumer.Infrastructure.Helpers;
using SoapConsumer.Infrastructure.Proxy.Abstract;
using SoapConsumer.Infrastructure.Proxy.Attributes;
using SoapConsumer.Infrastructure.Proxy.Builders.Abstract;
using SoapConsumer.Infrastructure.Transformers.Abstract;
namespace SoapConsumer.Infrastructure.Proxy
{
public class WebServiceProxy : IWebServiceProxy
{
private readonly IPipelineTransformer _pipelineTransformer;
private readonly ISoapXmlBuilder _builder;
private readonly IConfiguration _configuration;
public WebServiceProxy(IPipelineTransformer pipelineTransformer,
ISoapXmlBuilder builder ,IConfiguration configuration)
{
_pipelineTransformer = pipelineTransformer;
_builder = builder;
_configuration = configuration;
}
public async Task<TModel> ExecuteAsync<TModel, TParams>(TParams parameters)
{
if (!(parameters?.GetType().GetCustomAttributes(typeof(SoapAttribute)).FirstOrDefault() is SoapAttribute
soapAttribute))
throw new InvalidOperationException("Object doesn't have soap attribute.");
var host = this._configuration.GetSection(soapAttribute.Host ?? "WebService:Hosts:0:DefaultHost")
.GetValue();
var endpoint = this._configuration.GetSection(soapAttribute.Endpoint).GetValue();
var operation = this._configuration.GetSection(soapAttribute.Operation).GetValue();
var request = CreateWebRequest(host, endpoint, operation);
var soapEnvelopeXml = new XmlDocument();
var xmlEnvelope = _builder.Build(parameters, soapAttribute.Namespace);
soapEnvelopeXml.LoadXml(xmlEnvelope);
using (var stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
return await GetResponseAsync<TModel>(request);
}
private async Task<TModel> GetResponseAsync<TModel>(HttpWebRequest request)
{
using (var response = await request.GetResponseAsync())
{
using (var rd = new StreamReader(response.GetResponseStream()))
{
return _pipelineTransformer.Transform<TModel>(rd.ReadToEnd());
}
}
}
private HttpWebRequest CreateWebRequest(string host, string endpoint, string operation)
{
var webRequest = (HttpWebRequest)WebRequest.Create($@"{host}{endpoint}?op={operation}");
webRequest.Headers.Add(@"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="5.2.0" />
<PackageReference Include="Autofac.Configuration" Version="5.1.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.4" />
</ItemGroup>
</Project>
namespace SoapConsumer.Infrastructure.Transformers.Abstract
{
public interface IPipelineTransformer
{
TModel Transform<TModel>(string input);
}
}
namespace SoapConsumer.Infrastructure.Transformers.Abstract
{
public interface ITransformer
{
}
public interface ITransformer<out TModel> : ITransformer
{
TModel Transform(string responseData);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using SoapConsumer.Infrastructure.Transformers.Abstract;
namespace SoapConsumer.Infrastructure.Transformers
{
public class PipelineTransformer : IPipelineTransformer
{
private readonly IEnumerable<ITransformer> _transformers;
public PipelineTransformer(IEnumerable<ITransformer> transformers)
{
_transformers = transformers;
}
public TModel Transform<TModel>(string input)
{
var transformer = _transformers.OfType<ITransformer<TModel>>().FirstOrDefault();
if (transformer == null)
{
throw new InvalidOperationException($"Transformer for {typeof(TModel)} type was not found.");
}
return transformer.Transform(input);
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SoapConsumer.Infrastructure.CQRS.Queries;
using SoapConsumer.Queries;
namespace SoapConsumer.Controllers
{
[Route("test")]
public class TestController : Controller
{
private readonly IQueryBus _queryBus;
public TestController(IQueryBus queryBus)
{
_queryBus = queryBus;
}
[HttpGet("testaction")]
public async Task<IActionResult> TestAction()
{
var result = await _queryBus.ExecuteAsync<TestQuery, TestQueryResponse>(new TestQuery { Id = 1 });
return Ok(result.Data);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
namespace SoapConsumer.Helpers
{
public class AssembliesProvider
{
public static IEnumerable<Assembly> GetReferencingAssemblies(string assemblyName)
{
var assemblies = new List<Assembly>();
var dependencies = DependencyContext.Default.RuntimeLibraries;
foreach (var library in dependencies)
{
if (IsCandidateLibrary(library, assemblyName))
{
var assembly = Assembly.Load(new AssemblyName(library.Name));
assemblies.Add(assembly);
}
}
return assemblies;
}
private static bool IsCandidateLibrary(RuntimeLibrary library, string assemblyName)
{
return library.Name.StartsWith(assemblyName) || library.Dependencies.Any(d => d.Name.StartsWith(assemblyName));
}
}
}
using Autofac;
using SoapConsumer.Queries.Handlers;
namespace SoapConsumer.Modules
{
public class SoapConsumerModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
RegisterQueryHandlers(builder);
}
private void RegisterQueryHandlers(ContainerBuilder builder)
{
builder.RegisterType<TestQueryHandler>().AsImplementedInterfaces();
}
}
}
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace SoapConsumer
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58253",
"sslPort": 44371
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"SoapConsumer": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Threading.Tasks;
using SoapConsumer.Infrastructure.CQRS.Queries.Generic;
using SoapConsumer.Infrastructure.Proxy.Abstract;
namespace SoapConsumer.Queries.Handlers
{
public class TestQueryHandler : IHandleQuery<TestQuery, TestQueryResponse>
{
private readonly IWebServiceProxy _webServiceProxy;
public TestQueryHandler(IWebServiceProxy webServiceProxy)
{
_webServiceProxy = webServiceProxy;
}
public async Task<TestQueryResponse> HandleAsync(TestQuery query)
{
_webServiceProxy.ExecuteAsync<>();
return new TestQueryResponse
{
Data = "done from response"
};
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SoapConsumer.Infrastructure.CQRS.Queries.Generic;
namespace SoapConsumer.Queries
{
public class TestQuery : IQuery<TestQueryResponse>
{
public int Id { get; set; }
}
}
namespace SoapConsumer.Queries
{
public class TestQueryResponse
{
public string Data { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="5.2.0" />
<PackageReference Include="Autofac.Configuration" Version="5.1.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.4" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SoapConsumer.Infrastructure\SoapConsumer.Infrastructure.csproj" />
</ItemGroup>
</Project>

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoapConsumer", "SoapConsumer.csproj", "{E9529460-D698-4481-BF70-19857C0AF817}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SoapConsumer.Infrastructure", "..\SoapConsumer.Infrastructure\SoapConsumer.Infrastructure.csproj", "{E7E3FE56-7B0A-4AB2-B3DE-C520768C6229}"
EndProject
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "DummyWCF", "..\DummyWCF\", "{AB1E61CD-8CED-44DE-8A34-C9CCC226F0E7}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.7.2"
Debug.AspNetCompiler.VirtualPath = "/localhost_60314"
Debug.AspNetCompiler.PhysicalPath = "..\DummyWCF\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_60314\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.FixedNames = "false"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/localhost_60314"
Release.AspNetCompiler.PhysicalPath = "..\DummyWCF\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_60314\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.FixedNames = "false"
Release.AspNetCompiler.Debug = "False"
VWDPort = "60314"
SlnRelativePath = "..\DummyWCF\"
DefaultWebSiteLanguage = "Visual C#"
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E9529460-D698-4481-BF70-19857C0AF817}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E9529460-D698-4481-BF70-19857C0AF817}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E9529460-D698-4481-BF70-19857C0AF817}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E9529460-D698-4481-BF70-19857C0AF817}.Release|Any CPU.Build.0 = Release|Any CPU
{E7E3FE56-7B0A-4AB2-B3DE-C520768C6229}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7E3FE56-7B0A-4AB2-B3DE-C520768C6229}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7E3FE56-7B0A-4AB2-B3DE-C520768C6229}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7E3FE56-7B0A-4AB2-B3DE-C520768C6229}.Release|Any CPU.Build.0 = Release|Any CPU
{AB1E61CD-8CED-44DE-8A34-C9CCC226F0E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB1E61CD-8CED-44DE-8A34-C9CCC226F0E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB1E61CD-8CED-44DE-8A34-C9CCC226F0E7}.Release|Any CPU.ActiveCfg = Debug|Any CPU
{AB1E61CD-8CED-44DE-8A34-C9CCC226F0E7}.Release|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0A1F3C72-587D-4DDC-A09A-038648312D0E}
EndGlobalSection
EndGlobal
using System;
using System.Linq;
using System.Reflection;
using Autofac;
using Autofac.Configuration;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SoapConsumer.Helpers;
namespace SoapConsumer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Assemblies = AssembliesProvider.GetReferencingAssemblies("SoapConsumer").ToArray();
}
public IConfiguration Configuration { get; }
private Assembly[] Assemblies { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterAssemblyModules(Assemblies);
builder.RegisterModule(new ConfigurationModule(Configuration));
}
//private void ConfigureAutofacContainer(IServiceCollection services)
//{
// var builder = new ContainerBuilder();
// builder.Populate(services);
// builder.RegisterAssemblyModules(Assemblies);
// builder.RegisterModule(new ConfigurationModule(Configuration));
// AutofacContainer = builder.Build();
//}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment