Currently, I am working on an old project and I met too many errors, my goal is to succeed the deployment on my local machine, Brief in this below class, the GetHelpPageSampleGenerator() is underlined in red:
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
In the same classe i have the method GetHelpPageSampleGenerator() but overload, it means that the method SetSampleObjects and by using config argument which i can't understand it calls GetHelpPageSampleGenerator() :
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
the error that i get:
Severity Code Description Project File Line Suppression State
Error CS0121 The call is ambiguous between the following methods or
properties:
'WebInstructionSheet.Areas.HelpPage.HelpPageConfigurationExtensions.GetHelpPageSampleGenerator(System.Web.Http.HttpConfiguration)'
and
'WebInstructionSheet.Areas.HelpPage.HelpPageConfigurationExtensions.GetHelpPageSampleGenerator(System.Web.Http.HttpConfiguration)'
Related
I am trying to add a new page in the public store of nopCommerce. For that I have create Entity, model, factory, controller, Interface and service etc.
But as soon as I am running my nopCommerce project, it shows me following error.
Autofac.Core.Activators.Reflection.NoConstructorsFoundException: 'No accessible constructors were found for the type 'Nop.Web.Factories.SupportRequestModelFactory'.'
I'm using nopCommerce version 4.50 version.
What are the causing of this error and how can it be resolved?
Here is a picture about that error.
I tried to find the error in Controller and factory, but couldn't find the exact solution for this!
NoConstructorsFoundException happens when you don't have a public constructor for a class. To resolve this issue make sure you have a public constructor in your SupportRequestModelFactory class and pass all the necessary services in the parameter of the public constructor.
Here is an Example:
public partial class SupportRequestModelFactory : ISupportRequestModelFactory
{
private readonly ILocalizationService _localizationService;
private readonly ILocalizedModelFactory _localizedModelFactory;
public SupportRequestModelFactory(
ILocalizationService localizationService,
ILocalizedModelFactory localizedModelFactory)
{
_localizationService = localizationService;
_localizedModelFactory = localizedModelFactory;
}
}
Also, make sure you have registered your model factory in the ConfigureServices.
public class NopStartup : INopStartup
{
public virtual void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<ISupportRequestModelFactory, SupportRequestModelFactory>();
}
}
I ran into a issue because LogManager is global, so my two projects were overriding each other's logging config. NLog log calls in the first project would work fine, but then when calling into the second project, all future log calls would be logged with the second projects config.
Example:
Target 1 "First log in first project" (supposed to be target 1)
Target 2 "Second log in second project" (supposed to be target 2)
Target 2 "Third log in first project" (supposed to be target 1)
I found Isolated logfactory which solved my issue, now the loggers has the correct config. However I cannot figure out how to use my custom NLog class with this method of making LogFactories.
This works great (but doesn't let me use my custom class with methods):
private static Logger logger = MyLogger.MyLogManager.Instance.GetCurrentClassLogger();
This:
private static MyLogger logger = (MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger();
Throws:
System.TypeInitializationException: 'The type initializer for 'MyProject.MyClass.MyMethod' threw an exception.'
InvalidCastException: Unable to cast object of type 'NLog.Logger' to type 'MyProject.NLogConfigFolder.MyLogger'.
I have tried to cast Logger to MyLogger but have not been able to do so successfully.
Here is my setup for the isolated LogFactory:
public class MyLogger : Logger
{
public class MyLogManager
{
public static LogFactory Instance { get { return _instance.Value; } }
private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
private static LogFactory BuildLogFactory()
{
string configFilePath = "path/to/my/config"
LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory);
return logFactory;
}
}
// Other methods here
}
Thank you for your time and help with this problem.
Think you just need to change:
(MyLogger)MyLogger.MyLogManager.Instance.GetCurrentClassLogger()
Into this:
MyLogger.MyLogManager.Instance.GetCurrentClassLogger<MyLogger>()
See also: https://nlog-project.org/documentation/v5.0.0/html/Overload_NLog_LogFactory_GetCurrentClassLogger.htm
I have default Program.cs file from Web Api template in .NET 6.0.
I am adding variable "test" so I can use its value in controllers.
var builder = WebApplication.CreateBuilder(args);
const string test = "test123";
builder.Configuration.Bind(test);
//rest of the file...
And now I want to use variable "test" outside Program.cs but I have no idea how to do it. I cannot just simply use it because when trying to read it in controller like this:
string localVar = test;
I am getting an error "'test' is not null here. Cannot use local variable or local function declared in a top-level statement in this context".
This is probably some stupid mistake but I can't figure it out...
Starting C# 9, we don't need to explicitly mention the Main method in Program.cs file as we can use the top-level statements feature. However, it doesn't mean that we shouldn't use the default Program class in the created file at all. In your case, you have a need to define the static/const property so you can change the newly created structure into the old one.
namespace WebApplication;
public class Program
{
public static string Test { get; private set; }
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
Program.Test = "approach1";
builder.Services.Configure<MyOptions>(x => x.Test = "approach2");
///
}
public class MyOptions
{
public string Test { get; set; }
}
I assumed that you have a need to set the value to the Program.Test field during runtime, so in the first approach, I used the static field with a private set; accessor instead of the constant.
In the second approach, I used the C# options feature to configure the MyOptions.Test field value, this will be very flexible and useful to write unit tests later. But, you need to inject the MyOptions class wherever is required.
In the below controller template, I specified how to access the configured values at Program.cs file, inside the Get method
public class TestController : ControllerBase
{
private readonly MyOptions _myOptions;
public TestController (IOptions<MyOptions> myOptions)
{
_myOptions = myOptions.Value;
}
public IActionResult Get()
{
string test1 = Program.Test;
string test2 = _myOptions.Test;
///
}
}
Add public partial class Program { } at the very end of your Program.cs file and add constant, property or whatever you like in there.
I am going with "Freeman pro asp.net mvc 5" book (chapter 7).
The problem is:
The code in NinjectWebCommon.cs never executes, so I am constantly getting error "No parameterless constructor defined for this object." It seems like web server doesn't see this file at all, I have breakpoints on every method and never get to any of them when running application.
First, I followed all the instructions in the book, and made the project by myself. I got this error.
Second, I downloaded code examples from official site, opened the project and trying to run it. I still got this error.
Third, I created a new , absolutely simple mvc5+ninject application, and I still got this error.
Any ideas?
So to be clear, just these steps:
1. I am going to http://www.apress.com/us/book/9781430265290
2. I am downloading source code
3. I am opening source code example from chapter 7 in VS 2015
4. Without making any changes to the code, I am pressing F5 and enjoying the error in the browser:
[MissingMethodException: No parameterless constructor defined for this object.]
..
[InvalidOperationException: An error occurred when trying to create a controller of type 'SportsStore.WebUI.Controllers.ProductController'. Make sure that the controller has a parameterless public constructor.]
the controller code is simple:
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository repository)
{
this.repository = repository;
}
public ViewResult List()
{
return View(repository.Products);
}
}
Next, I have my own implementation of dependency resolver in code:
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernelParam)
{
kernel = kernelParam;
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
Mock<IProductRepository> mock = new Mock<IProductRepository>();
mock.Setup(m => m.Products).Returns(new List<Product>
{
new Product {Name = "Football", Price = 25},
new Product {Name = "Surf board", Price = 179},
new Product {Name = "Running shoes", Price = 95}
});
kernel.Bind<IProductRepository>().ToConstant(mock.Object);
}
}
And finally, I use it in class NinjectWebCommon, like this:
private static void RegisterServices(IKernel kernel)
{
System.Web.Mvc.DependencyResolver.SetResolver(new Infrastructure.NinjectDependencyResolver(kernel));
}
InvalidOperationException: An error occurred when trying to create a
controller of type 'SportsStore.WebUI.Controllers.ProductController'.
Make sure that the controller has a parameterless public constructor
The error message is clear: your controller does not have a parameterless constructor (as confirmed by your code). This is of course intentional since you require an IProductRepository. You simply need to provide a binding for the IProductRepository so that Ninject knows how to create this dependency.
The problem is solved, the reason was: never use damn # symbol in your path to projects.
Ninject, Visual studio or whatever cannot resolve it properly and fail to load dependancies.
In my C# class project, I have a helper class which has the following property
public class Helper
{
public string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
}
}
My following test fails when I call the Helper class from NUNIT project with error message: Failure: System.NullReferenceException : Object reference not set to an instance of an object.
[Test]
public void connection_string_exists()
{
string connection = new Helper().ConnectionString;
Assert.NotNull(connection);
}
If I run the line of code new Helper().ConnectionString from a asp.net project then it works. Why does the Test fail?
Please let me know.
I suspect your Nunit tests are part of a different project and when you run the tests, ConfigurationManager looks at the config file of your test project and does not find "MyConnectionString"