How do I add a service stack license to a .NET core project? - servicestack

For my service stack license I am used to adding a web config entry
<add key="servicestack:license" ... />
How do I achieve a similar effect in ServiceStack.Core since there is no web config?

The license key can be registered using any of the options listed at: https://servicestack.net/download#register
So while there's no Web.config you can use any of the other 3 options like registering the SERVICESTACK_LICENSE Environment Variable.
Also whilst .NET Core doesn't need to use Web.config or App.config you can still use one in .NET Core in ServiceStack for storing any <appSettings>, e.g:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="servicestack:license" value="{LicenseKey}" />
</appSettings>
</configuration>
But you'll need to register the license key explicitly from the AppSettings with:
using ServiceStack;
public class AppHost : AppHostBase
{
public AppHost()
: base("Service Name", typeof(MyServices).GetAssembly())
{
var licenseKeyText = AppSettings.GetString("servicestack:license");
Licensing.RegisterLicense(licenseKeyText);
}
public override void Configure(Container container)
{
}
}
Or if you don't want to use Web.config you can use any other AppSettings options.

Related

How to Use NuGet Package in VSTS Package Management with Azure Functions?

One of the nice things of Azure Functions is that you can bring your own dependencies with NuGet, npm, etc. If you have an internal NuGet package inside of VSTS Package Management that you want to use as a dependency in your Azure Function, how would you go about including it in your Azure Function usings?
Example: I may want to leverage my internal Data Access Libraries, models, or business logic and then use VSTS Package Management as the way our team manages our internal dependencies. We wouldn't want to publish those out to the public nuget.org gallery 😀
Thanks for the help!
You can reference packages in a private NuGet repository using the information available here.
Once you add your private source to the config file, you can add references to your custom packages following the information outlined here.
(Additional edits from OP...)
Example project.json
{
"frameworks": {
"net46":{
"dependencies": {
"Contoso.Models": "1.2.0",
"Contoso.DAL ": "1.2.0"
}
}
}
}
project.json is added to root folder for your function.
Example nuget.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="MyVSTSPackageManagementFeed" value="https://contoso.pkgs.visualstudio.com/_packaging/Contoso/nuget/v3/index.json" />
</packageSources>
<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>
<packageSourceCredentials>
<MyVSTSPackageManagementFeed>
<add key="Username" value="me#contoso.com" />
<add key="ClearTextPassword" value="<MyPersonalAccessTokenHere>" />
</MyVSTSPackageManagementFeed>
</packageSourceCredentials>
</configuration>
nuget.config is added to either the root folder for your function or if you want to use them across all of your functions, you can add it to the host level folder.

How to define connection string for session state in Azure

I am using the RedisSessionStateProvider using a procedimient like this https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-session-state-caching/
I define its connection string in web.config, in this example is XXXXXX.
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.5" />
<globalization culture="es-CO" uiCulture="es" />
<customErrors mode="Off" />
<sessionState mode="Custom" customProvider="SessionStateStore">
<providers>
<add name="SessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" connectionString="XXXXXX" throwOnError="true" applicationName="NominappSession" />
</providers>
</sessionState>
</system.web>
I dont want to put the connection string in the source code. So how can i using the settings in Azure to define this connection string?
I deploy to azure from github, so it uses Kudu. I dont have an external CI server.
Any advice please?
I did it :)
To do that you need to define the connection string as a environment variable, not as a typical connection string. And in the sesion state provide use the environment variable name.
This way:
<appSettings>
<add key="REDIS_CONNECTION_STRING" value="redis,allowAdmin=true" />
</appSettings>
<system.web>
<sessionState mode="Custom" customProvider="SessionStateStore">
<providers>
<add name="SessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" connectionString="REDIS_CONNECTION_STRING" applicationName="REDIS_SESSION_APPLICATION_NAME" throwOnError="true" />
</providers>
</sessionState>
</system.web>
Using that you can now define the connection string in the App Settings of Azure WebSites
If you just want to be able to provide your connection string from your source code, you can use the settingsClassName and settingsMethodName properties in the config, like so:
<sessionState mode="Custom" customProvider="RedisSessionStateStore">
<providers>
<add
name="RedisSessionStateStore"
type="Microsoft.Web.Redis.RedisSessionStateProvider"
settingsClassName="MyApp.SessionStateRedisSettings,MyApp"
settingsMethodName="ConnectionString" />
</providers>
In here, the settingsClassName is the name of a class in your app, with its fully qualified namespace. The settingsMethod name is the name of the method on this class, which must be static, take 0 parameters and return an string. For example:
namespace MyApp
{
public static class SessionStateRedisSettings
{
public static string ConnectionString()
{
return "ConnectionString goes here";
}
}
}
From here: https://github.com/Azure/aspnet-redis-providers/wiki/Configuration
Take a look at Scott Hanselman's blog on the subject:
http://www.hanselman.com/blog/HowToKeepYourASPNETDatabaseConnectionStringsSecureWhenDeployingToAzureFromSource.aspx
You can store the connection string inside of the app settings within the azure portal and then call them from within your app. This prevents the string from being contained within your source code. You'll want to do the same with your storage keys as well.
In the portal go to the settings of your app, and select "Application Settings". Scroll down on that pane to Connection Strings.
Check out the connection strings section of this page as well:
https://azure.microsoft.com/en-us/documentation/articles/web-sites-configure/
I think IPartitionResolver can come to rescue here...
You can basically create a class that implements System.Web.IPartitionResolver interface and specify it in the sessin state configuration in web.config as this
<sessionState mode="Custom" partitionResolverType="WebAppConnectionStringResolver">
And then in the class you can override the connection string
public class WebAppConnectionStringResolver : System.Web.IPartitionResolver
{
public void Initialize()
{
}
public string ResolvePartition(object key)
{
return System.Configuration.ConfigurationManager.ConnectionStrings["your_Conn_string_name_in_portal"]
}
}
I havent tested this out but I believe this should work
Read more at
https://msdn.microsoft.com/en-us/library/system.web.configuration.sessionstatesection.partitionresolvertype(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.web.ipartitionresolver(v=vs.110).aspx

Configuring NLog with ServiceStack to not be NullDebugLogger

I'm new to NLog and have chosen to add it to my ServiceStack (4.0.44) web services however it's not working as I expect as I always end up with a NullDebugLogger.
I have
Global.Asax
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
LogManager.LogFactory = New NLogFactory()
Dim appHost As New MyAppHost
appHost.Init()
End Sub
I've also manually added an NLog.config file to log to the debugger
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="true"
internalLogLevel="Trace" internalLogFile="c:\temp\nlog-internal.log" >
<targets>
<!-- log to the debugger -->
<target xsi:type="Debugger" name="debugger" layout="${logger}::${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugger" />
</rules>
</nlog>
and finally in my class I have the following
public class MyClass
{
public static ILog Log;
public MyClass()
{
Log = LogManager.GetLogger(typeof(MyClass));
}
public void LogSomething()
{
Log.Debug("Starting to LogSomething");
}
}
When I debug, the Log object in my class shows as a ServiceStack.Logging.NullDebugLogger which I believe is the default but I can't figure out how to change it to something I can use. I'm sure I'm missing something simple but can't figure out what it is. My web services are in a different project (in the same solution) which is why my Global.asax is VB and the class is C#. I also have no reference in web.config to NLog.config but I assume that Nlog picks that up anyway.
The way logging works is very simple, LogManager.LogFactory just sets a static property where all subsequent calls to LogManager.GetLogger(Type) will use that concrete factory to return the preferred logger implementation. So it just needs to be sent once on Application Start before any calls to LogManager.GetLogger() is made.
LogManager.LogFactory defaults to NullLogFactory but never gets set by ServiceStack, so the only reasons why it wouldn't retain the NLogFactory is if LogManager.GetLogger() isn't being retrieved in the same AppDomain where it was set or it's only being set after LogManager.GetLogger() is called or some of your code is reverting it back to LogManager.LogFactory = new NullLogFactory().
My hunch since you've shown both C# and VB.NET code is that it's not being set in the same Web Application, i.e. your static property set in VB.NET is not visible in the AppDomain where your C# code is running.

NLog with DNX Core 5.0

I am attempting to implement NLog logging using ASP.Net 5 and MVC 6. Be default, both DNX 451 and DNX Core 50 are included in the project template.
I am attempting to implement NLog Logging by following the example here.
However, in the sample app, there is the following line -
#if !DNXCORE50
factory.AddNLog(new global::NLog.LogFactory());
#endif
And if I run the app, this line never gets hit because the mvc application has dnx core 50 installed by default.
Is there any loggers that are available for DNX Core 50? If not, what purpose does dnx core serve in the default mvc app - is it actually needed?
Edit: If I remove the #if !DNXCORE50.... line above, I get a the following error -
DNX Core 5.0 error - The type or namespace name 'NLog' could not be found in the global namespace'
DNX Core 5.0 is only necessary if you want the cloud-optimized cross-platform version of the .Net framework; if you still plan on using the MVC app within only a Windows environment, you can remove your dnxcore50 framework reference from your project.json.
NLog for .NET Core (DNX environment) is currently available in version 4.4.0-alpha1.
Steps:
Create NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<targets>
<target xsi:type="ColoredConsole" name="ToConsole" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="ToConsole" />
</rules>
Load and parse configuration
private static ILogger _logger;
public static void LoggerSetup()
{
var reader = XmlReader.Create("NLog.config");
var config = new XmlLoggingConfiguration(reader, null); //filename is not required.
LogManager.Configuration = config;
_logger = LogManager.GetCurrentClassLogger();
}
public static void Main(string[] args)
{
LoggerSetup();
// Log anything you want
}
When dealing with the MVC tooling in MVC6 (dnx stuff), the answer to this is very fluid.
In order to get NLog to work with my web app, I had to do a couple steps:
-> Big thanks to two NLog discussions(here and here)
I just needed to add the configuration setup in my Startup.cs's constructor:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
// Set up logging configuration
// from: https://github.com/NLog/NLog/issues/641
// and: https://github.com/NLog/NLog/issues/1172
var reader = XmlTextReader.Create(File.OpenRead(Path.Combine(builder.GetBasePath(),"NLog.config"))); //stream preferred above byte[] / string.
LogManager.Configuration = new XmlLoggingConfiguration(reader, null); //filename is not required.
log.Info("NLogger starting");
Configuration = builder.Build();
}
I consider this a bit of a stop-gap as Microsoft is introducing a new Logging interface (that I hope will end up being like SLF4J.org is in Java). Unfortunately, documentation on that is a bit thin at the time I'm writing this. NLog is working diligently on getting themselves an implementation of the new dnx ILoggingProvider interface.
Additional information about my project setup
My NLog.config file is located in the project root folder, next to
the project.json and appsettings.json. I had to do a little digging
inside AddJsonFile() to see how they handled pathing.
I used yeoman.io and their aspnet generator to set up the web project.
Version of NLog, thanks to Lukasz Pyrzyk above:
"NLog": "4.4.0-alpha1"

Owin Startup Detection

I developed an application with Owin Startup class. When i am running the OwinHost.exe, it shows No Assembly found containing OwinStartupAttribute.
But I defined the assembly in my startup class as:
[assembly: OwinStartup(typeof(OwinDemo.BrandStartup))]
I also defined appSettings in the Web.Config file as:
<appSettings>
<add key="owin:AppStartup" value="OwinDemo.Startup, OwinDemo"/>
Project-> right click add new item.
Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

Resources