ASP.NET Core Directory.EnumerateDirectories not working when deployed to Azure AppService - azure

I am currently experimenting with ASP.NET Core MVC by creating a simple blog with static views. I've created a custom class that implements the IViewLocationExpander in order to enumerate a directory structure to retrieve razor views
public class FolderEnumerationViewExpander : IViewLocationExpander
{
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
IEnumerable<string> viewLocations)
{
var locations = viewLocations.ToList();
foreach (var directory in Directory.EnumerateDirectories("Views/Blog", "*", SearchOption.AllDirectories))
{
locations.Add($"/{directory.Replace("\\","/")}" + "/{0}.cshtml");
}
return locations.AsEnumerable();
}
}
I've configured this class to be used within Startup.cs's ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IPostsMetaDataRepositry>(new JsonPostsMetaDataRepository(ConfigurationPath.Combine("posts.json")));
services.Configure<RazorViewEngineOptions>(o => { o.ViewLocationExpanders.Add(new FolderEnumerationViewExpander()); });
services.AddMvc();
}
This seems to work perfectly when I run my application locally using IISExpress however, when I deploy the application to an Azure AppService, only a handful of the directories within ~/Views/Blog are being enumerated when trying to locate views.
I'm fairly certain the issue is one of configuration but I am having a difficult time tracking down what it could be. Any ideas as to why this may be occurring?
I have the full source of this project on GitHub for reference: https://github.com/pstricker/Develothink

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>();
//...
}
}

Get Azure AppSettings in a Controller

I have an ASP.NET Core 2 application hosted on Azure, and I added a new Application Settings MyNewSetting for my App in the Azure Portal.
How do I access that setting from a controller?
My code bellow:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<AppSecrets>(Configuration);
services.AddSingleton<ITableRepositories, TableClientOperationsService>();
//...
My Controller:
public class RecordController : Controller
{
const int MyNewSetting = 7; // this one to replace with Azure Setting one
private readonly ITableRepositories repository;
public RecordController(ITableRepositories rep) {
repository = rep;
}
Here, I need probably to add FromServices injection, but I am not sure if it will work...
EDIT:
Folowing the #dee_zg answer, the following code could probably do the job:
public class RecordController : Controller
{
int MyNewSetting = 7;
private readonly ITableRepositories repository;
public RecordController(ITableRepositories rep) {
repository = rep;
int myInt;
if (int.TryParse(System.Environment.GetEnvironmentVariable("MY_NEW_SETTING"),
out myInt)) {
MyNewSetting = myInt;
};
}
You can choose to either get them from AppSettings["your-key"] collection or as environment variables: Environment.GetEnvironmentVariable("your-key").
From there you can map them to your custom IOptions and inject wherever you need them.
There's quite a few things you can do.
Use Options and configuration objects
The options pattern uses custom options classes to represent a group of related settings. We recommended that you create decoupled classes for each feature within your app.
Use an IOptionsSnapshot.
IOptionsSnapshot supports reloading configuration data when the configuration file has changed. It has minimal overhead. Using IOptionsSnapshot with reloadOnChange: true, the options are bound to Configuration and reloaded when changed.
... (see documentation)
In short, have a look at Configuration in ASP.NET Core, determine the scenario that best fits your needs and have at it!
Hope this helps.

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.)

Azure Mobile Services - No bootstrapper found

I have a Azure Mobile Services project. When running locally everything works fine, the Application_Start() method gets called which in turn calls my WebApiConfig.Register() method.
However, when published to a live Azure Mobile Services server the Application_Start() does not get called along with the WebApiConfig.Register().
In the servers log I have the following entry:
No bootstrapper found -- using default bootstrapper. A bootstrapper can be specified in one of two ways: Either by defining a public, static class with name 'WebApiConfig' having a public parameter-less member called 'Register', or using the 'IBootstrapper' attribute to define a public class with a default constructor.
Why is Azure Mobile Services not picking up my BootStrapping WebApiConfig?
public static class WebApiConfig
{
public static void Register()
{
Trace.TraceInformation("Hello from WebApiConfig Register().");
// Use this class to set configuration options for your mobile service
ConfigOptions options = new ConfigOptions();
// Use this class to set WebAPI configuration options
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
// To display errors in the browser during development, uncomment the following
// line. Comment it out again when you deploy your service for production use.
// config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
public class WebApiApplication : System.Web.HttpApplication
{
public WebApiApplication()
{
Trace.TraceInformation("Hello from WebApiApplication ctor!");
}
protected void Application_Start()
{
Trace.TraceInformation("Hello from Application_Start()");
//RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register();
var dataContext = new DataContext();
dataContext.Database.Initialize(false);
}
}
Help is much appreciated!
That is bizarre... It really looks like you got it right. After working with .net backend azure mobile service for few weeks, I might suggest just maybe restart the service in portal and republish. I have hit some weird unexplained stuff just like you are and somehow fix like that.

ServiceStack - Different server to main application

I wish to create a service which will be hosted on Server A (eg URL: http://servera:807). But my main application needs to be hosted on Server B (eg URL: http://serverb:801).
I am curious if this is possible or not? The reason my service and main application need to be on different servers are for reasons beyond my control. The current system uses WCF with the same setup and I'd like to move away from this.
In the examples the Service and Client all seem to be hosted in the same location / in the same solution
Below is a potential set up for solutions/projects. It's simplistic and incomplete but I think helps illustrate one possible set up. You would also need to consider how you want to handle Session information and Authentication since the MVC and ServiceStack handle this separately. See CustomAuthenticationMVC
ServerA.sln (ASP.NET Web Application)
ServiceModel project - holds requests objects and dtos (this can be shared between ServerA and ServerB solutions)
ServiceInterface project - has the Service implementations
Global.asx - has Application_Start method to configure ServiceStack
ServerB.sln (MV4 application)
ServiceModel project (shared)
Views
Models
Controllers
Example of classes in ServiceModel Project:
[Route("/Foos")]
public class Foos : IReturn<FoosResponse>
{}
public class FoosResponse
{
public FoosResponse()
{
this.ResponseStatus = new ResponseStatus();
}
public ResponseStatus ResponseStatus {get; set;}
}
Examples of classes in ServiceInterface project
public class FoosService : Service
{
public FoosResponse Get(Foos request)
{
return new FoosReponse();
}
}
Example how to call ServiceStack API within MVC4 application
public class FoosController
{
public ActionResult Index()
{
var client = new JsonServiceClient("http://servera:807");
var response = client.Get(new Foos());
return View(response);
}
}

Resources