Startup.vb Don´t recognize StarttupAuth.vb Class [duplicate] - vb.net

I'm getting an error when I'm attempting to run my page says that,
The name 'ConfigureAuth' does not exist in the current context
in my Stratup Class. I'm sure all AspNet Identity libraries are installed. What do I need to do next, to try to fix this?
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(project_name.Startup))]
namespace project_name
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}

If you are using default Visual Studio project template, the ConfigureAuth method could be found in partial class Startup.Auth.cs. So make sure you didn't break anything when modifying project structure.
This is an example of ConfigureAuth method:
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/api/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}

I had similar issue, To fix the issue I removed .App_Start from namespace in Startup.Auth.cs file. After that I was able to see the reference.

It is either:
[assembly: **OwinStartup**(typeof(Project-Name.Startup))]
namespace project-name
{
public partial class Startup
{
public void **Configuration**(IAppBuilder app)
{
OR
[assembly: **OwinStartupAttribute**(typeof(Project-Name.Startup))]
namespace project-name
{
public partial class Startup
{
public void **ConfigureAuth**(IAppBuilder app)
{
Either rename OwinStartupAttribute to OwinStartup
OR Configuration to ConfigureAuth

Kindly I note that the two partial classes (Startup.Auth.cs and Startup.cs) should be in the same namespace which is the root of the project, just change the namespace of Startup.Auth.cs to the same namespace of the Startup.cs

Make sure when you originally create the project that there are no spaces in the name.
e.g. my app was called "DevOps Test" which was giving me errors when I ran it.
I recreated it as "DevopsTest" and no longer had these issues

namespace PAYOnline.App_Start
delete App_Start only namespace PAYOnline => It's welldone

Related

Razor pages not update until restart project

I add Volo.Account module with source code to my solution for update some functionality of Login/Register. When I update page (like Login.cshtml) changes not shown until restart project.
According to Microsoft doc, I instal Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package and line below to ConfigureServices of {PROJECT}AuthServerModule, but RuntimeCompilation not working.
context.Services.AddRazorPages()
.AddRazorRuntimeCompilation();
actually you don't need to use AddRazorRuntimeCompilation in your application. You can get the advantage of ABP's Virtual File System and configure the AbpVirtualFileSystemOptions in your application module class:
public override void ConfigureServices(ServiceConfigurationContext context)
{
var hostingEnvironment = context.Services.GetHostingEnvironment();
var configuration = context.Services.GetConfiguration();
//other configurations...
if (hostingEnvironment.IsDevelopment())
{
Configure<AbpVirtualFileSystemOptions>(options =>
{
options.FileSets.ReplaceEmbeddedByPhysical<AbpAccountWebModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("<web-module-project-path>")));
});
}
}
You just need to use the ReplaceEmbeddedByPhysical method. Check the following links for more info:
https://docs.abp.io/en/abp/latest/Virtual-File-System#dealing-with-embedded-files-during-development
https://github.com/abpframework/abp/blob/dev/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/MyProjectNameWebModule.cs#L148

How to get the appsetting as an object in the ConfigureServices method of the startup.cs file and pass that to another service being added right after

I want to load up a custom class in my aspnetcore startup that I want to be able to use through the lifetime of the application. This custom class needs some object which is based on data in the appsettings.json file.
I am using aspnetcore webapi 3.1 and I have currently this setup in my startup.cs class public void ConfigureServices(IServiceCollection services) method, which works:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
var _appConfig = Configuration.GetSection("AppSettings").Get<AppSettings>();
services.Add(new ServiceDescriptor(typeof(IMyCustomClasses), new MyCustomClass(_appConfig.Somevalue)));
In my controller, I got this constructor:
public HomeController(IOptions<AppSettings> config, IMyCustomClasses mc)
{
_config = config;
_mc = mc;
}
While all of this works and I can get the instantiated custom class MyCustomClass along with an instantiated AppSettings class in my HomeController, I want to know if there is a way I can avoid using this line:
var _appConfig = Configuration.GetSection("AppSettings").Get<AppSettings>();
to setup MyCustomClass on the line after it and somehow get it directly from the line before, which is:
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Any tips, ideas?

Read Config From Another Project - Log4Net ASP.NET Core 3.1

I am trying to write a class library that uses log4net that looks something like this:
public class Logging
{
private ILog log4netLogger = null;
public Logging(Type type)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
log4netLogger = LogManager.GetLogger(type);
}
public void Debug(string message)
{
log4netLogger(message);
}
public void Info(string message)
{
log4netLogger(message);
}
}
However, the xml configuration is in my test console app in C:\....\TestLogging\TestLog4Net\bin\Debug\netcoreapp3.1. I actually started with this console app to test log4net but I have moved all my code from the main method of Program.cs to the Logging.cs constructor, but I think the LogManager will not be able to find this now.
Is this at all possible?
I think it is possible. To use the log4net in the class library, you have to install the log4net package in the class library, then, you could add the class library reference in the console application and use the class library method. But, as you said, the log4net.config file should be in the console application netcoreapp3.1 folder, otherwise, the class library will not find the log4net.config file:

How to configure hangfire with unity?

I have ASP.NET Web API application. The application is using Unity as IoC container. The application is also using Hangfire and I am trying to configure Hangfire to use Unity.
So based on documentation i am using Hangfire.Unity which registers the unity container as a current job activator in Hangfire.
I have a class which has dependency on IBackgroundJobClient
public class MyService
{
private MyDBContext _dbContext = null;
private IBackgroundJobClient _backgroundJobClient = null;
public MyService(MyDbContext dbContext, IBackgroundJobClient backgroundJobClient)
{
_dbContext = dbContext;
_backgroundJobClient = backgroundJobClient;
}
}
However even after configuring Hangfire.Unity it could not create & pass instance of BackgroundJobClient
So i had to register every dependency of BackgroundJobClient with unity container.
Unity Registration
public class UnityConfig
{
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<MyDbContext>(new HierarchicalLifetimeManager(), new InjectionFactory(x => new MyDbContext()));
// register hangfire dependencies
container.RegisterType<IBackgroundJobClient, BackgroundJobClient>();
container.RegisterType<JobStorage, SqlServerStorage>(new InjectionConstructor("HangfireConnectionString"));
container.RegisterType<IJobFilterProvider, JobFilterAttributeFilterProvider>(new InjectionConstructor(true));
container.RegisterType<IBackgroundJobFactory, BackgroundJobFactory>();
container.RegisterType<IRecurringJobManager, RecurringJobManager>();
container.RegisterType<IBackgroundJobStateChanger, BackgroundJobStateChanger>();
}
}
OWIN Startup
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = UnityConfig.GetConfiguredContainer();
Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireConnectionString");
Hangfire.GlobalConfiguration.Configuration.UseUnityActivator(container);
// if i dont call UseSqlServerStorage() above then UseHangfireDashboard() method fails with exception
//JobStorage.Current property value has not been initialized. You must set it before using Hangfire Client or Server API.
app.UseHangfireDashboard();
app.UseHangfireServer();
RecurringJob.AddOrUpdate<MyService>(x => x.Prepare(), Cron.MinuteInterval(10));
}
}
Code is working with such configuration. However i have questions:
Is this the correct way of configuring Unity with Hangfire?
Why do i need to invoke Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireConnectionString") in OWIN startup even though SqlServerStorage is already registered with Unity container as JobStorage?
If i dont invoke UseSqlServerStorage() method in OWIN startup then i get exception on app.UseHangfireDashboard() method.
JobStorage.Current property value has not been initialized. You must
set it before using Hangfire Client or Server API.
I believe there is a problem where you want to kick off Hangfire outside of the Unity ecosystem, but also want Unity to understand how to instantiate the appropriate Hangfire interfaces with the associated implementations. Since Hangfire itself doesn't use Unity, you will need to start up Hangfire with the appropriate configuration, such as the SQL Server connection string, and then use that configuration to inform Unity how to instantiate the Hangfire interfaces. I was able to solve this problem by setting the global Hangfire configuration for SQL and then use that same Hangfire static instance to set up Unity.
Here's example code where first you will see how I start the hangfire dashboard and server with a connection string:
public void Configuration(IAppBuilder app)
{
var configuration = new Configuration(); // whatever this is for you
GlobalConfiguration.Configuration.UseSqlServerStorage(
configuration.GetConnectionString());
GlobalConfiguration.Configuration.UseActivator(
new HangfireContainerActivator(UnityConfig.GetConfiguredContainer()));
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] {new HangfireAuthorizationFilter()}
});
app.UseHangfireServer();
}
As the second example, here's the configuration of Unity for Hangfire; notice how this code is using the static JobStorage Hangfire object to instantiate any requests for JobStorage.
public static void RegisterHangfire(IUnityContainer container)
{
container.RegisterType<JobStorage>(new InjectionFactory(c => JobStorage.Current));
container.RegisterType<IJobFilterProvider, JobFilterAttributeFilterProvider>(new InjectionConstructor(true));
container.RegisterType<IBackgroundJobFactory, BackgroundJobFactory>();
container.RegisterType<IRecurringJobManager, RecurringJobManager>();
container.RegisterType<IBackgroundJobClient, BackgroundJobClient>();
container.RegisterType<IBackgroundJobStateChanger, BackgroundJobStateChanger>();
}
I believe this approach gives you the best of both worlds where you only set up your SQL Server connection once and you do it early to kick off Hangfire, but then you use that instance to tell Unity how to behave.

Cannot access RavenDB Management Studio

Try:
I created a new project in VS2012
I installed via the NuGet package RavenDB Embedded -Pre
I installed Ninject.MVC3
Added a module for ninject RavenDB:
Public class RavenDBNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentStore>().ToMethod(context =>
{
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);
var documentStore = new EmbeddableDocumentStore { Url="http://localhost:8080/", DataDirectory="~/App_Data", UseEmbeddedHttpServer = true };
return documentStore.Initialize();
}).InSingletonScope();
Bind<IDocumentSession>().ToMethod(context => context.Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
}
In my class "NinjectWebCommon" ...
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new RavenDBNinjectModule());
}
When running the application, the following url was generated ("http://localhost:1423")
Verify that the file "Raven.Studio.xap" was the root of my application
I tried accessing "http://localhost:8080" but the following screen is displayed:
What am I doing wrong?
As it turned out, the issue is that documentStore.Initialize never get called, because that no one did ask Ninject to resolve IDocumentStore.
You are setting the Url property, which means that you aren't running in embedded mode, but in server mode.
Remove the Url property, and everything will work for you.
I found the problem!
Since he had used IDocumentSession in no time, the ninject had not created the instance of IDocumentStore and thus not run the Initialize method