ServiceStack and .NET Core AppSettings complex object - servicestack

I'm using this from the docs (https://docs.servicestack.net/host-configuration) to load my appsettings.json into ServiceStack:
AppSettings = new NetCoreAppSettings(Configuration)
My appsettings.json has this line:
"test": [ "a", "b" ]
However when I do a var allSettings = AppSettings.GetAll(); and look for my key test it is null.
I know .NET core only supports list/dictionary by using .Bind(), and this works:
List<string> test = new List<string>();
Configuration.GetSection("test").Bind(test);
Since ServiceStack has methods such as GetList, GetDictionary, and even Get<T>, I assume there is something I'm doing wrong since it doesn't work.

All of ServiceStack's AppSettings providers deserializes string scalar values using JSV Format so if you wanted to use its GetList() or Get<T> your appsettings.json config would need to look like:
"test": "a,b,c"
Or
"test": "[a,b,c]"
Which you can resolve from:
var test = AppSettings.GetList("test"); // or
var test = AppSettings.Get<List<string>>("test");

Related

How to read configuration from appsetings.json for custom serilog sink in asp.net core 2.0

I created the custom sentry sink inside my API project.
public class SentrySink : ILogEventSink {...}
I also created an extension method for my sink so that I can connect my sink
through logging configuration.
public static LoggerConfiguration Sentry(this LoggerSinkConfiguration loggerConfiguration,
string dsn,
string release = null,
string environment = null,
LogEventLevel restrictedToMinimumLevel = LogEventLevel.Information,
IFormatProvider formatProvider = null)
{...}
When I use
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.Sentry(configuration["Sentry:Dsn"], restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error)
Everything works fine and log's are in sentry.
But when I set up the configuration in appsetting.json as
"WriteTo": [
{ "Name": "Sentry" }, ...
without defining config in LoggerConfiguration the log's are not sent to sentry.
Do I need to implement something more so that I can use configs from appsetting.json?
Thanks.
You'll need to include at least "Args": {"dsn": ...}, because the dsn parameter is not optional.
You may also need a "Using": ["YourAssemblyContainingSink"] statement to ensure the configuration method is found, depending on the deployment target, and to check that the sink assembly is copied to your project's output directory.

How do I add framework assemblies in Azure Function

I need to add System.Web.Script.Serialization and System.Web.Extensions to my function app so that I can deserialize json string using the following code :
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic item = serializer.Deserialize<object>("{ \"test\":\"some data\" }");
string test= item["test"];
This does not work :
#r "System.Web.Script.Serialization"
#r "System.Web.Extensions"
How do I add resolve this issue?
I can't get that work, so I ended up using Newtonsoft Json serializer/deserializer. What you need to do is, follow this instruction to upload project.json file to your function app with this content -
{
"frameworks": {
"net46":{
"dependencies": {
"Newtonsoft.Json": "9.0.1"
}
}
}
}
This basically creates dependency. Then add this name space to your code : "using Newtonsoft.Json.Linq". Voila, you can convert your json string to object like this :
dynamic item = JObject.Parse("{number:1000}");
log.Info($"My number is: {item.number}");
The initial reference likely failed because you were trying to add an assembly reference to System.Web.Script.Serialization, which is a namespace. Adding a reference to System.Web.Extensions should work, but using Json.NET is recommended anyway.

ASP.NET 5 can't use Response

I'm trying to output information from my database to an Excel File using ASP.Net 5. In my controller I have two methods for this.
public void ExportData()
{
var data = new[]{
new{ Name="Ram", Email="ram#techbrij.com", Phone="111-222-3333" },
new{ Name="Shyam", Email="shyam#techbrij.com", Phone="159-222-1596" },
new{ Name="Mohan", Email="mohan#techbrij.com", Phone="456-222-4569" },
new{ Name="Sohan", Email="sohan#techbrij.com", Phone="789-456-3333" },
new{ Name="Karan", Email="karan#techbrij.com", Phone="111-222-1234" },
new{ Name="Brij", Email="brij#techbrij.com", Phone="111-222-3333" }
};
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Contact.xls");
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/vnd.ms-excel");
WriteTsv(data, System.Web.HttpContext.Current.Response.Output);
System.Web.HttpContext.Current.Response.End();
}
public void WriteTsv<T>(IEnumerable<T> data, TextWriter output)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.DisplayName); // header
output.Write("\t");
}
output.WriteLine();
foreach (T item in data)
{
foreach (PropertyDescriptor prop in props)
{
output.Write(prop.Converter.ConvertToString(
prop.GetValue(item)));
output.Write("\t");
}
output.WriteLine();
}
}
I am forced to use System.Web because I have no idea how to export an excel file using ASP.Net 5, thus I'm currently using dnx451. I deleted dnxcore50 from my project.json in order to use System.Web.
However when calling the top method, I get the following error:
NullReferenceException: Object reference not set to an instance of an object.
on
System.Web.HttpContext.Current.Response.ClearContent();
The original example of this code used:
Response
Instead of:
System.Web.HttpContext.Current.Response
I cannot use just use Response because it uses Microsoft.AspNet.Http.HttpResponse instead of System.Web
Using System.Web.HttpResponse also doesn't work because it gives the following error:
An object reference is required for the non-static field, method, or property
This is my first web application and this problem has caused me to grind into a halt. Can anyone help me?
You can't use System.Web. One of the goals of ASP.Net Core was to remove the dependency on System.Web. Since ASP.Net Core is does not depend on System.Web the HttpContext et al. won't be initialized and hence NRE. You can use IHttpContextAccessor to get HttpContext in ASP.Net Core and access the Response from there.

Bind an object to class in autofac and object can be null

I am using MiniProfiler in my project. To get an instance of the MiniProfiler, i have to use the following:
var profiler = MiniProfiler.Current;
This profiler object is what I want AutoFac to pass to every MiniProfiler Type when I create a class. Example I did the following:
var profiler = MiniProfiler.Current;
builder.RegisterInstance(profiler);
and in my controller I use the following way:
public ListingsController(IDataFetcher DataFetcher, ILog log, MiniProfiler profiler)
{
_DataFetcher = DataFetcher;
_log = log;
_profiler = profiler;
}
The thing is the profiler instance can be null and I get the following server error when i run the code.
Value cannot be null.
See image:
What needs to be done so that I can use Autofac with Miniprofiler? Or am I registering the object to the concreteType correctly?
Try registering a lambda so it's always the current instance instead of one specific instance.
builder.Register(
c => MiniProfiler.Current)
.As<MiniProfiler>();

Create shared NUnit tests for plugins

I have plugins and i need to test, that any plugin fits to some specification. One of these cases is to check whether some interface exists in assembly (need to reflect from assembly).
I'd like to create some console application which will take plugin as an argument and check it.
This application will contain a set of tests, that will be configured by a passed argument. And the test runner which will produce xml report to output.
Is there better solution?
Update.
In my console application i call:
static int Main(string[] args)
{
CoreExtensions.Host.InitializeService();
var runner = new SimpleTestRunner();
var testPackage = new TestPackage(Assembly.GetExecutingAssembly().FullName);
string loc = Assembly.GetExecutingAssembly().Location;
testPackage.Assemblies.Add(loc);
if (runner.Load(testPackage))
{
var result = runner.Run(new NullListener(), new AllTestsFilter(), false, LoggingThreshold.Off);
var buffer = new StringBuilder();
new XmlResultWriter(new StringWriter(buffer)).SaveTestResult(result);
Console.Write(buffer.ToString());
return result.IsSuccess
? 0
: -1;
}
return -1;
}
In this soultion i have tests, but i need to pass arguments from command line to this tests through runner..
Probably you can use the TestCaseSource attribute: http://nunit.org/index.php?p=testCaseSource&r=2.6.3
Inside the test case source property you can enumerate the assemblies to test: NUnit will take care to generate a parametric test for each value.
Regarding the command line execution, you can use nunit-console.exe. You can get it here: http://www.nuget.org/packages/NUnit.Runners/
Hope it helps.
solved this problem by creation simple console application without NUnit.. Just return code -1/0

Resources