ProjectTo Automapper ASP.NET Core - automapper

I am using ProjectTo function of AutoMapper 5.2.0 in asp.net core.
I have already initialized my mappings at startup class. But it is throwing exception :
Mapping not initialized.

Initialize Map in startup.cs
Mapper.Initialize(config => {
config.CreateMap<source, Destination>().ReverseMap();
});

You are missing the initialization, however, I would recommend you to use the configuration by profile approach especially if you are interested in testing you code.
Could you please add more details to the question?
This is a typical configuration with static methods
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<ClassEntity, ClassDto>().ReverseMap();
});
...
}
Here you can find a good answer step by step

Related

I have to integrate ServiceStack together with Kephas. How do I make them both play together with Dependency Injection?

ServiceStack uses a dialect of Funq (no support for metadata), where Kephas uses one of MEF/Autofac (requires metadata support). My question has two parts:
How to make ServiceStack and Kephas use one DI container, if this is possible?
Depending on the answer above: how to make ServiceStack services (like IClientCache) available to Kephas components, knowing that such services may not be annotated with [AppServiceContract]?
You can make ASP.NET and Kephas use one container by choosing to work with Autofac. However, as #mythz pointed out, you will need to provide the Autofac IoC Adapter to the ServiceStack. I don't think you will have any problems with ASP.NET in doing so, as Autofac is the first recommendation of the ASP.NET Core team.
For ASP.NET Core, reference the Kephas.AspNetCore package and inherit from the StartupBase class if you need to be all setup. However, if you need to be in control, have a look at https://github.com/kephas-software/kephas/blob/master/src/Kephas.AspNetCore/StartupBase.cs and write your own Startup class. Another resource that you might find useful is the Kephas.ServiceStack integration package.
Then, additionally to annotating service contracts and service implementations, Kephas allows you to provide service definitions by implementing the IAppServiceInfoProvider interface. These classes are automatically discovered, so this is pretty much everything you have to do.
public class ServiceStackAppServiceInfoProvider : IAppServiceInfoProvider
{
public IEnumerable<(Type contractType, IAppServiceInfo appServiceInfo)> GetAppServiceInfos(IList<Type> candidateTypes, ICompositionRegistrationContext registrationContext)
{
yield return (typeof(IUserAuthRepository),
new AppServiceInfo(
typeof(IUserAuthRepository),
AppServiceLifetime.Singleton));
yield return (typeof(ICacheClient),
new AppServiceInfo(
typeof(ICacheClient),
ctx => new MemoryCacheClient(),
AppServiceLifetime.Singleton));
}
}
Note in the above example that for IUserAuthRepository there is no implementation provided. This indicates Kephas to auto-discover the implementation in the types registered for composition. Alternatively, feel free to use an instance or a factory in the registration, if you need to be deterministic.
I've never heard of Kephas before, but if you're referring to this Kephas Framework on GitHub it says it uses ASP.NET Core in which case it's best if you get them to both use ASP.NET Core's IOC which you can do by either registering your dependencies in ConfigureServices in your App's Startup:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//...
}
}
Or alternatively in ServiceStack's latest v5.6 release for Modular Startup change your ASP.NET Core Startup class to inherit from ModularStartup, e.g:
public class Startup : ModularStartup
{
public Startup(IConfiguration configuration) : base(configuration){}
public new void ConfigureServices(IServiceCollection services)
{
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
}
}
In which case you'll be able to Register ASP.NET Core dependencies in AppHost by registering them in your AppHost's Configure(IServiceCollection) where they can be resolved through both ASP.NET Core's IOC + ServiceStack's IOC, e.g:
public class AppHost : AppHostBase
{
public override void Configure(IServiceCollection services)
{
services.AddSingleton<IRedisClientsManager>(
new RedisManagerPool(Configuration.GetConnectionString("redis")));
}
public override void Configure(Container container)
{
var redisManager = container.Resolve<IRedisClientsManager>();
//...
}
}

Adding custom property to all Application Insight traces

I want to add a custom property to all traces in Application Insights.
In Asp.Net Core I've added this code
internal class TelemetryProperties : ITelemetryInitializer
{
private IConfiguration configuration;
public TelemetryProperties(IConfiguration configuration)
{
this.configuration = configuration;
}
// TODO: Not being added to all traces.
// http://apmtips.com/blog/2014/12/01/telemetry-initializers/
public void Initialize(ITelemetry telemetry)
{
var applicationName = configuration["Application:Name"];
telemetry.Context.Properties.Add("Application", applicationName);
}
}
and in the configure method of Startup.cs I have added:
TelemetryConfiguration.Active.TelemetryInitializers.Add(new TelemetryProperties(Configuration));
The intent was to add "Application" to all traces, even ones made automatically by Application Insights, but the effect is that it is ONLY being added to my custom traces that Im calling through my code.
How do I add a property to ALL traces, even ones I do not create.
Edit: The purpose of this is that I want to have multiple APIs in the same application insights log, but I want to be able to partition when neccessary by adding a defining property such as application name.
Modifying TelemetryConfiguration.Active is not the recommended approach in Asp.Net Core apps. Can you add the telemetry initializer using the below code in ConfigureServices ?
services.AddSingleton<ITelemetryInitializer, TelemetryProperties>();
https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Custom-Configuration#adding-new-telemetryinitializer
Please let me know if this helps.
I used your code(without change), and at my side, all the traces(the application insights adds, I didn't use any Trackxx methods) including the exception all have the property "Application". Please see the screenshots below:
If it still occurs in your side, please provide the screenshots of the appInsights' logs.

ASP.NET Core Identity Implementation using Cassandra Database

I am building an ASP.NET Core MVC application using the Cassandra Database on Windows.
I need help implementing ASP.NET Core Identity with Cassandra.
On Google I found AspNet.Identity.Cassandra in the version 2.0.0.1, but it's not compatible with ASP.NET Core 1.0.
I'm working on data store adapter for ASP.NET Core Identity
which allows you to build ASP.NET Core web applications, including membership, login, and user data. With this library, you can store your user's membership related data on Apache Cassandra.
Please note the library is in alpha version and needs to be finished
If you want to try it, follow these steps:
1 - Run the following command from the package manager console to install Cassandra identity provider.
Install-Package AspNetCore.Identity.Cassandra -Version 1.0.0-alpha1
2 - Add settings to appsettings.json
{
"CassandraNodes": [
"127.0.0.1"
],
"CassandraOptions": {
"KeyspaceName": "identity",
"Replication": {
"class": "NetworkTopologyStrategy",
"datacenter1": "1"
}
}
}
3 - Configure services in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// CassandraOptions configuration
services.Configure<CassandraOptions>(Configuration.GetSection("CassandraOptions"));
// Cassandra ISession initialization
services.AddCassandraSession<Cassandra.ISession>(() =>
{
var cluster = Cassandra.Cluster.Builder()
.AddContactPoints(Configuration.GetSection("CassandraNodes").GetChildren().Select(x => x.Value))
.Build();
var session = cluster.Connect();
return session;
});
// Added custom Cassandra stores
services.AddIdentity<ApplicationUser, ApplicationRole>()
.UseCassandraStores<Cassandra.ISession>()
.AddDefaultTokenProviders();
// Other code omitted
}
4 - And finally initialize DB in Program.cs
public static class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build()
.InitializeIdentityDb<ApplicationUser, ApplicationRole>();
}
For more information check project site at github.
Few Option
Try implement your own cassandra identity for ASP.net core, there is many sample how to create your Custom IdentityUser for ASP.net (using Google) then make it work with Cassandra
Fork / Update the AspNet.Identity.Cassandra project to .net core (open source, so makes easy to implement your own)
Use another provider, instead of Cassandra Database
Request update on github (link on section 2.)

What is StarterTemplateAppListenerHost in Service Satck?

I am doing some stuff in Service Stack self host in windows service. The link gave me some hint. But in the code, what is StarterTemplateAppListenerHost then?
It is a class which extends AppHostHttpListenerBase (Source here) which is used to provide the http listener and application configuration.
public class StarterTemplateAppListenerHost : AppHostHttpListenerBase
{
static readonly IAppSettings AppSettings = new AppSettings();
public StarterTemplateAppListenerHost()
: base(AppSettings.GetString("ServiceName") ?? "StarterTemplate HttpListener", typeof(HelloService).Assembly) { }
public override void Configure(Funq.Container container)
{
container.Register(new TodoRepository());
}
}
This is demonstrated also in the official documentation here.
I just wonder why the link doesn't have OnStart() etc
The example has two different compilation modes. When it's run in debug, it will not run as a service, and solely uses StarterTemplateAppListenerHost.
When it is run in release mode then it will create a service around the instance of StarterTemplateAppListenerHost. The WinService class provides the OnStart and OnStop methods which are expected of Windows Services by extending System.ServiceProcess.ServiceBase.
So to get it running as a Windows Service you will need to include these 3 files:
Program.cs
WinService.cs
StarterTemplateAppListenerHost.cs

Orchard module loading event

I'm very new to Orchard CMS and I have started writing my first module. I've been looking for a way to detect when my module has been initialized from the root website but have had no luck!
A colleague suggested using WebActivator and the PreApplicationStartMethod attribute to configure a method to be called on start up but this did not work.
Has anybody managed to accomplish this, is there an interface provided by orchard like IModule that will allow me to hook into module initialization?
There are two event handlers that might interest you. IFeatureEventHandler and IOrchardShellEvents. The IFeatureEventHandler interface gives you hooks for modules enabling, disabling, installing, and uninstalling. The IOrchardShellEvents interface provides hooks for the activation and termination of the Orchard Shell. Something in there should do the trick for you!
You shouldn't mix up Autofac's and Orchard's modules.
To execute some code when Orchard's module starts you need to implement IOrchardShellEvents interface (Activated method). Also don't forget to register your implementation in Autofac:
public class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Bootstrapper>().As<IOrchardShellEvents>().InstancePerLifetimeScope();
}
}
Solved! Implement an Autofac.Module and override the Load(ContainerBuilder) method!
using Autofac;
public class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
// Module initialization here!
}
}

Resources