I saw some commits for ServiceStakck ORMLite for .NET Core specifically this
Can we try it right now or it is just nuget spec update? I am looking to integrate ServiceStack ORMLite for .Net core project (ServiceStack.OrmLite.PostgreSQL.Core).
All of OrmLite's supported packages contains both .NET Framework v4.5 and .NET Standard 2.0 builds which can be used in both .NET Framework and .NET Core projects which can be used like normal:
public class Person
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
public static string PostgreSqlDb = "{Connection String}";
public static void Main(string[] args)
{
var dbFactory = new OrmLiteConnectionFactory(
PostgreSqlDb, PostgreSqlDialect.Provider);
using (var db = dbFactory.Open())
{
db.DropAndCreateTable<Person>();
5.Times(i => db.Insert(new Person { Name = "Name {i}" }));
var results = db.Select<Person>();
results.PrintDump();
}
Console.ReadLine();
}
}
As say in NuGet package's details page, you can use it with .Net Core with at least .NETStandard 1.3.
But if you look into the latest release note. They say :
Just like the other .NET Core libraries .NET Core builds of
ServiceStack.Redis is released with a *.Core suffix until development
of .NET Core has stabilized.
Related
I want to create a custom FileTarget for NLog (targeting LiteDB). I can't use the existing one since it's missing some features I need and afaik it's not compatible with the latest version of LiteDB. In my custom target I would like to use the TempDir Layout Renderer. Since NLog already has this with the FilePathLayout class, I thought I can reuse it but sadly this is declared as internal.
Am I missing something? Is there any other way to use this?
My setup:
NLog: 4.7.2
NLog.Web.AspNetCore: 4.9.2
ASP.NET Core 3.1
If you are writing a custom NLog target, then you can do this:
[Target("MyFirst")]
public sealed class MyFirstTarget: TargetWithLayout
{
public MyFirstTarget()
{
this.Directory = "${tempdir}";
}
public Layout Directory { get; set; }
protected override void Write(LogEventInfo logEvent)
{
string logMessage = RenderLogEvent(this.Layout, logEvent);
string directory = RenderLogEvent(this.Directory, logEvent);
WriteToDirectory(directory, logMessage);
}
private void WriteToDirectory(string directory, string message)
{
// TODO - write me
}
}
See also: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
What is the best practice for creating multiple queueclients for listening to different service bus queues? There is a MessagingFactory class however Microsoft.ServiceBus.Messaging not seems to be available as a nuget package anymore (.net core console application).
Considering QueueClient as static object what would be the recommended pattern to create multiple queueclients from a singleton host process?
Appreciate the feedback.
For .net core applications, you can make use of Microsoft.Azure.ServiceBus instead of Microsoft.ServiceBus.Messaging nuget. As this is build over .net standard, this can be used in both framework and core applications. Methods and classes similar to Microsoft.ServiceBus.Messaging are available under this. Check here for samples.
Able to get it working however could not use dependency injection. Any suggestions on improving this implementation would be much appreciated.
Startup.cs
// Hosted services
services.AddSingleton();
ServiceBusListener.cs
public class ServiceBusListener : BackgroundService, IServiceBusListener
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine($"ServiceBusListener is starting.");
Dictionary<string, QueueClient> queueClients = new Dictionary<string, QueueClient>();
foreach (var queue in _svcBusSettings.Queues)
{
var svcBusQueueClient = new ServiceBusQueueClient(queue.Value, queue.Key);
queueClients.Add(queue.Key, svcBusQueueClient.QueueClient);
}
}
}
ServiceBusQueueClient.cs
public class ServiceBusQueueClient : IServiceBusQueueClient
{
private IQueueClient _queueClient;
public QueueClient QueueClient
{
get { return _queueClient as QueueClient; }
}
public ServiceBusQueueClient(string serviceBusConnection, string queueName)
{
_queueClient = new QueueClient(serviceBusConnection, queueName);
RegisterOnMessageHandlerAndReceiveMessages();
}
}
So we have a working ServiceStack service hosted inside a Windows Service using .Net 4.6.2, which uses a bunch of Fluent Validation validators.
We would like to port this to .Net Core. So I started to create cut down project just with a few of the features of our main app to see what the port to .Net Core would be like.
Most things are fine, such as
IOC
Routing
Hosting
Endpoint is working
The thing that does not seem to be correct is validation. To illustrate this I will walk through some existing .Net 4.6.2 code and then the .Net Core code. Where I have included the results for both
.NET 4.6.2 example
This is all good when using the full .Net 4.6.2 framework and the various ServiceStack Nuget packages.
For example I have this basic Dto (please ignore the strange name, long story not my choice)
using ServiceStack;
namespace .RiskStore.ApiModel.Analysis
{
[Route("/analysis/run", "POST")]
public class AnalysisRunRequest : BaseRequest, IReturn<AnalysisRunResponse>
{
public AnalysisPart Analysis { get; set; }
}
}
Where we have this base class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .RiskStore.ApiModel
{
public abstract class BaseRequest
{
public string CreatedBy { get; set;}
}
}
And we have this validator (we have way more than this working in .Net 4.6.2 app, this is just to show differences between full .Net and .Net Core which we will see in a minute)
using .RiskStore.ApiModel.Analysis;
using ServiceStack.FluentValidation;
namespace .RiskStore.ApiServer.Validators.Analysis
{
public class AnalysisRunRequestValidator : AbstractValidator<AnalysisRunRequest>
{
public AnalysisRunRequestValidator(AnalysisPartValidator analysisPartValidator)
{
RuleFor(analysis => analysis.CreatedBy)
.Must(HaveGoodCreatedBy)
.WithMessage("CreatedBy MUST be 'sbarber'")
.WithErrorCode(ErrorCodes.ValidationErrorCode);
}
private bool HaveGoodCreatedBy(AnalysisRunRequest analysisRunRequest, string createdBy)
{
return createdBy == "sbarber";
}
}
}
And here is my host file for this service
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Funq;
using .RiskStore.ApiModel.Analysis;
using .RiskStore.ApiModel.Analysis.Results;
using .RiskStore.ApiServer.Api.Analysis;
using .RiskStore.ApiServer.Exceptions;
using .RiskStore.ApiServer.IOC;
using .RiskStore.ApiServer.Services;
using .RiskStore.ApiServer.Services.Results;
using .RiskStore.ApiServer.Validators.Analysis;
using .RiskStore.ApiServer.Validators.Analysis.Results;
using .RiskStore.DataAccess.AnalysisRun.Repositories.Results;
using .RiskStore.DataAccess.AnalysisRun.Repositories.Search;
using .RiskStore.DataAccess.AnalysisRun.Repositories.Validation;
using .RiskStore.DataAccess.Configuration;
using .RiskStore.DataAccess.Connectivity;
using .RiskStore.DataAccess.Ingestion.Repositories.EventSet;
using .RiskStore.DataAccess.JobLog.Repositories;
using .RiskStore.DataAccess.StaticData.Repositories;
using .RiskStore.DataAccess.UnitOfWork;
using .RiskStore.Toolkit.Configuration;
using .RiskStore.Toolkit.Jobs.Repositories;
using .RiskStore.Toolkit.Storage;
using .RiskStore.Toolkit.Utils;
using .Toolkit;
using .Toolkit.Configuration;
using .Toolkit.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ServiceStack;
using ServiceStack.Text;
using ServiceStack.Validation;
namespace .RiskStore.ApiServer.Api
{
public class ApiServerHttpHost : AppHostHttpListenerBase
{
private readonly ILogger _log = Log.ForContext<ApiServerHttpHost>();
public static string RoutePrefix => "analysisapi";
/// <summary>
/// Base constructor requires a Name and Assembly where web service implementation is located
/// </summary>
public ApiServerHttpHost()
: base(typeof(ApiServerHttpHost).FullName, typeof(AnalysisServiceStackService).Assembly)
{
_log.Debug("ApiServerHttpHost constructed");
}
public override void SetConfig(HostConfig config)
{
base.SetConfig(config);
JsConfig.TreatEnumAsInteger = true;
JsConfig.EmitCamelCaseNames = true;
JsConfig.IncludeNullValues = true;
JsConfig.AlwaysUseUtc = true;
JsConfig<Guid>.SerializeFn = guid => guid.ToString();
JsConfig<Guid>.DeSerializeFn = Guid.Parse;
config.HandlerFactoryPath = RoutePrefix;
var exceptionMappings = new Dictionary<Type, int>
{
{typeof(JobServiceException), 400},
{typeof(NullReferenceException), 400},
};
config.MapExceptionToStatusCode = exceptionMappings;
_log.Debug("ApiServerHttpHost SetConfig ok");
}
/// <summary>
/// Application specific configuration
/// This method should initialize any IoC resources utilized by your web service classes.
/// </summary>
public override void Configure(Container container)
{
//Config examples
//this.Plugins.Add(new PostmanFeature());
//this.Plugins.Add(new CorsFeature());
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(AnalysisRunRequestValidator).Assembly);
.......
.......
.......
.......
container.Register<AnalysisPartValidator>(c => new AnalysisPartValidator(
c.Resolve<AnalysisDealPartLinkingModelEventSetValidator>(),
c.Resolve<AnalysisOutputSettingsPartValidMetaRisksValidator>(),
c.Resolve<AnalysisOutputSettingsGroupPartValidMetaRisksValidator>(),
c.Resolve<AnalysisDealPartCollectionValidator>(),
c.Resolve<AnalysisPortfolioPartCollectionValidator>(),
c.Resolve<UniqueCombinedOutputSettingsPropertiesValidator>()))
.ReusedWithin(ReuseScope.None);
container.Register<AnalysisRunRequestValidator>(c => new AnalysisRunRequestValidator(c.Resolve<AnalysisPartValidator>()))
.ReusedWithin(ReuseScope.None);
_log.Debug("ApiServerHttpHost Configure ok");
SetConfig(new HostConfig
{
DefaultContentType = MimeTypes.Json
});
}}
}
So I then hit this endpoint with this JSON
{
"Analysis": {
//Not important for discussion
//Not important for discussion
//Not important for discussion
//Not important for discussion
},
"CreatedBy": "frank"
}
And I get this response in PostMan tool (which I was expecting)
So that's all good.
.NET Core example
So now lets see what its like in .Net core example.
Lets start with the request dto
using System;
namespace ServiceStack.Demo.Model.Core
{
[Route("/analysis/run", "POST")]
public class AnalysisRunRequest : BaseRequest, IReturn<AnalysisRunResponse>
{
public AnalysisDto Analysis { get; set; }
}
}
Which uses this base request object
using System;
using System.Collections.Generic;
using System.Text;
namespace ServiceStack.Demo.Model.Core
{
public abstract class BaseRequest
{
public string CreatedBy { get; set; }
}
}
And here is the same validator we used from .NET 4.6.2 example, but in my .Net Core code instead
using System;
using System.Collections.Generic;
using System.Text;
using ServiceStack.Demo.Model.Core;
using ServiceStack.FluentValidation;
namespace ServiceStack.Demo.Core.Validators
{
public class AnalysisRunRequestValidator : AbstractValidator<AnalysisRunRequest>
{
public AnalysisRunRequestValidator(AnalysisDtoValidator analysisDtoValidator)
{
RuleFor(analysis => analysis.CreatedBy)
.Must(HaveGoodCreatedBy)
.WithMessage("CreatedBy MUST be 'sbarber'")
.WithErrorCode(ErrorCodes.ValidationErrorCode);
}
private bool HaveGoodCreatedBy(AnalysisRunRequest analysisRunRequest, string createdBy)
{
return createdBy == "sbarber";
}
}
}
And here is my host code for .Net core example
using System;
using System.Collections.Generic;
using System.Text;
using Funq;
using ServiceStack.Demo.Core.Api.Analysis;
using ServiceStack.Demo.Core.IOC;
using ServiceStack.Demo.Core.Services;
using ServiceStack.Demo.Core.Validators;
using ServiceStack.Text;
using ServiceStack.Validation;
namespace ServiceStack.Demo.Core.Api
{
public class ApiServerHttpHost : AppHostBase
{
public static string RoutePrefix => "analysisapi";
public ApiServerHttpHost()
: base(typeof(ApiServerHttpHost).FullName, typeof(AnalysisServiceStackService).GetAssembly())
{
Console.WriteLine("ApiServerHttpHost constructed");
}
public override void SetConfig(HostConfig config)
{
base.SetConfig(config);
JsConfig.TreatEnumAsInteger = true;
JsConfig.EmitCamelCaseNames = true;
JsConfig.IncludeNullValues = true;
JsConfig.AlwaysUseUtc = true;
JsConfig<Guid>.SerializeFn = guid => guid.ToString();
JsConfig<Guid>.DeSerializeFn = Guid.Parse;
config.HandlerFactoryPath = RoutePrefix;
var exceptionMappings = new Dictionary<Type, int>
{
{typeof(NullReferenceException), 400},
};
config.MapExceptionToStatusCode = exceptionMappings;
Console.WriteLine("ApiServerHttpHost SetConfig ok");
}
public override void Configure(Container container)
{
//Config examples
//this.Plugins.Add(new PostmanFeature());
//this.Plugins.Add(new CorsFeature());
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(ApiServerHttpHost).GetAssembly());
container.RegisterAutoWiredAs<DateProvider, IDateProvider>()
.ReusedWithin(ReuseScope.Container);
container.RegisterAutoWiredAs<FakeRepository, IFakeRepository>()
.ReusedWithin(ReuseScope.Container);
container.Register<LifetimeScopeManager>(cont => new LifetimeScopeManager(cont))
.ReusedWithin(ReuseScope.Hierarchy);
container.Register<DummySettingsPropertiesValidator>(c => new DummySettingsPropertiesValidator(c.Resolve<LifetimeScopeManager>()))
.ReusedWithin(ReuseScope.None);
container.Register<AnalysisDtoValidator>(c => new AnalysisDtoValidator(
c.Resolve<DummySettingsPropertiesValidator>()))
.ReusedWithin(ReuseScope.None);
container.Register<AnalysisRunRequestValidator>(c => new AnalysisRunRequestValidator(c.Resolve<AnalysisDtoValidator>()))
.ReusedWithin(ReuseScope.None);
SetConfig(new HostConfig
{
DefaultContentType = MimeTypes.Json
});
}
}
}
And this is me trying to now hit the .Net Core endpoint with the same bad JSON payload as demonstrated above with the .Net 4.6.2 example, which gave correct Http response (i.e included error that I was expecting in response)
Anyway here is payload being sent to .Net Core endpoint
{
"Analysis": {
//Not important for discussion
//Not important for discussion
//Not important for discussion
//Not important for discussion
},
"CreatedBy": "frank"
}
Where we can see that we are getting into the .Net Core example validator code just fine
But this time I get a very different Http response (one that I was not expecting at all). I get this
It can be seen that we do indeed get the correct Status code of "400" (failed) which is good. But we DO NOT get anything about the validation failure at all.
I was expecting this to give me the same http response as the original .Net 4.6.2 example above.
But what I seem to be getting back is the JSON representing the AnalysisRunResponse. Which looks like this
using System;
using System.Collections.Generic;
using System.Text;
namespace ServiceStack.Demo.Model.Core
{
public class AnalysisRunResponse : BaseResponse
{
public Guid AnalysisUid { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ServiceStack.Demo.Model.Core
{
public abstract class BaseResponse
{
public ResponseStatus ResponseStatus { get; set; }
}
}
I thought the way ServiceStack works (in fact that is how it works for ALL our existing .Net 4.6.2 code) is that the validation is done first, if AND ONLY if it passes validation is the actual route code run
But this .Net core example seems to not work like that.
I have a break point set in Visual Studio for the actual route and Console.WriteLine(..) but that is never hit and I never see the result of the Console.WriteLine(..)
What am I doing wrong?
This doesn't seem to any longer an issue with the latest v5 of ServiceStack that's now available on MyGet.
As sending this request:
Is returning the expected response:
The .NET Core packages are merged with the main packages in ServiceStack v5 so you'll need to remove the .Core prefix to download them, i.e:
<PackageReference Include="ServiceStack" Version="5.*" />
<PackageReference Include="ServiceStack.Server" Version="5.*" />
You'll also need to add ServiceStack's MyGet feed to fetch the latest ServiceStack v5 NuGet packages which you can do by adding this NuGet.config in the same folder as your .sln:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="ServiceStack MyGet feed" value="https://www.myget.org/F/servicestack" />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</packageSources>
</configuration>
During migration of an ASPNetCore 1.1 Project to ASPNetCore 2.0, we stumbled upon a Problem with the Cookie-AuthN and its SessionStore.
ASP.NET Core 1 allowed us to do something like that:
public void ConfigureServices(...) {
Services.AddDistributedSqlServerCache(...);
Services.AddSingleton<DistributedCookieSessionStore>(); /// SQL based store
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) {
var cookieOptions = app.ApplicationServices.GetRequiredService<IOptions<CookieAuthenticationOptions>>().Value;
cookieOptions.SessionStore = app.ApplicationServices.GetRequiredService<DistributedCookieSessionStore>();
app.UseCookieAuthentication(cookieOptions);
}
Messy, but doing its Job.
Now with ASP.NET Core 2 app.UseAuthentication() does not have a signature allowing to modify the options, and I am not able to use DI, to get a hold of the session store.
After long search I came accross this discussion https://github.com/aspnet/Security/issues/1338 where they mentioned IPostConfigureOptions interface. I put that together and this works for me:
1) Implement interface IPostConfigureOptions<CookieAuthenticationOptions>
public class PostConfigureCookieAuthenticationOptions : IPostConfigureOptions<CookieAuthenticationOptions>
{
private readonly ITicketStore _ticketStore;
public PostConfigureCookieAuthenticationOptions(ITicketStore ticketStore)
{
_ticketStore = ticketStore;
}
public void PostConfigure(string name, CookieAuthenticationOptions options)
{
options.SessionStore = _ticketStore;
}
}
2) Register this implementation to the container in Startup.ConfigureServices method
services.AddSingleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>();
I recently updated the nuget package for Microsoft.WindowsAzure.Storage to the 3.0 package which also included updates to WCF Data Services Client and it's dependencies. Since the update I get an error when the query is resolving stating:
"There is a type mismatch between the client and the service. Type
'ShiftDigital.Flow.Data.RouteDiagnostic' is not an entity type, but
the type in the response payload represents an entity type. Please
ensure that types defined on the client match the data model of the
service, or update the service reference on the client."
I've done nothing but update the packages and both my application along with a test script I setup in LinqPad generate this exception.
Here is the definition of the entity I've been returning just fine before the update
public class RouteDiagnostic : TableEntity
{
public long? LeadRecipientRouteId { get; set; }
public bool Successful { get; set; }
public int Duration { get; set; }
public string Request { get; set; }
public string Response { get; set; }
public RouteDiagnostic()
: base()
{
this.Timestamp = DateTimeOffset.Now;
this.PartitionKey = GetPartitionKey(this.Timestamp.Date);
this.RowKey = Guid.NewGuid().ToString();
}
public static string GetPartitionKey(DateTime? keyDateTime = null)
{
return string.Format("{0:yyyyyMM}", keyDateTime ?? DateTime.Now);
}
}
Here is the code performing the query
var storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse("...");
var tableClient = storageAccount.CreateCloudTableClient();
var tableContext = new Microsoft.WindowsAzure.Storage.Table.DataServices.TableServiceContext(tableClient);
var diagnostics =
tableContext.CreateQuery<RouteDiagnostic>("RouteDiagnostic")
.Where(rd => rd.PartitionKey == "0201401")
.ToList();
Has something changed that in the latest update or a different way to structure the entities when using data service queries?
Turns out with the update to WCF Data Services 5.6 I needed to add the following attribute to my type:
[DataServiceKey("PartitionKey", "RowKey")]
Once I added the DataServiceKey attribute, all was well again.
When using WCF Data Services, please make your class inherit from TableServiceEntity rather than TableEntity, which already has the DataServiceKey attribute defined. TableEntity is used for the new Table Service Layer in the Windows Azure Storage Client Library. For more information on the new Table Service Layer, please see our blog post.