i got error "Value cannot be null.\r\nParameter name: serviceType" - nopcommerce

I was following a tutorial , but after setting the project build path, I run the project and navigate to plugins. Then I got the following error.
An exception of type 'System.ArgumentNullException' occurred in Autofac.dll but was not handled in user code,
"Value cannot be null.\r\nParameter name: serviceType"
and i don't know that which method i should add and in which class?
Please help!

you must register the service you created in the plugin and also the repository for your entity in DependencyRegistrar.cs file so that run time Autofac can found them for example:
public class DependencyRegistrar : IDependencyRegistrar
{
public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
{
//data context
this.RegisterPluginDataContext<MYPLUGINObjectContext>(builder, "nop_object_context_misc_MYPLUGIN");
//override required repository with our custom context
builder.RegisterType<EfRepository<ENTITY>>()
.As<IRepository<ENTITY>>()
.WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_misc_MYPLUGIN"))
.InstancePerHttpRequest();
}
public int Order
{
get { return 0; }
}
}

Related

Check session before running controller issue in ASP.NET core

So I want to check if a session exists before running any action in the controller. I found these solutions link1,link2 and tried implementing them.
This is my SessionAuthorize class, everything seems fine here:
public class SessionAuthorize : ActionFilterAttribute
{
private readonly SessionManager _sessionManager;
public SessionAuthorize(SessionManager sessionManager)
{
_sessionManager = sessionManager;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!_sessionManager.IsLoggedIn)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "Login" }
});
}
}
}
Now, the issue am having is when I try to call it in the controller. So I am supposed to call by adding the [SessionAuthorize] attribute like this:
[SessionAuthorize]
public class AccountController : Controller
{
//code
}
But it gives me the error that I am not calling it properly. I believe it has to do with the dependency injection I used in SessionAuthorize to access the session. But I am not sure how to call it now.
The error message is:
'There is no argument given that corresponds to the required formal
parameter 'sessionManager' of
'SessionAuthorize.SessionAuthorize(SessionManager)'
So I would like to know how am I supposed to use it in my controller
If you want to avoid the Service Locator pattern you can use DI by constructor injection with a TypeFilter.
In your controller try using
[TypeFilter(typeof(SessionAuthorize)]
And your ActionFilterAttribute does not need to access a service provider instance anymore.

Prism XF: issue with creating 'child' view-models

I can see in the source code of Prism this
Container.RegisterType<INavigationService, UnityPageNavigationService>(_navigationServiceName);
Why is it using a specific name? Why not have this:
Container.RegisterType<INavigationService, UnityPageNavigationService>();
I am asking because I'm having a hard time with child view-models:
class ItemViewModel : BindableBase
{
public ItemViewModel(INavigationService navigationService)
{
}
}
and I'm creating items on a page:
class MainPageViewModel : BindableBase
{
public IEnumerable<ItemViewModel> Items { get; private set; }
public MainPageViewModel(Funct<ItemViewModel> itemFactory)
{
}
public void OnNavigatedTo(NavigationParameters parameters) {
Items = ... // Create items, where each item is created using itemFactory
}
}
But the DI fails, it throws exception because it cannot create ItemViewModel:
Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the
dependency failed, type = "MyApp.ViewModels.ItemViewModel", name =
"(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Prism.Navigation.INavigationService, is an interface and cannot be
constructed.
Are you missing a type mapping?
In Xamarin Forms navigation is based on the page being Navigated from. As such the Prism Forms PageNavigationService must be aware of the page which is associated with that particular instance of the service. In order to facilitate this, we register the service with a "secret" key, and then resolve the service and pass it in using the named instance "navigationService" for the ViewModel to consume.
You should not be using the NavigationService outside of the context of a ViewModel unless of course you are performing an absolute navigation (resetting Application.MainPage).
Note that each DI Container handles this a little differently, and each one uses a slight variation of the registration key, all of which is easy enough to look up with Prism being Open Source.

Nancyfx using Json.net, registering dependencies error

I'm trying to use nancy with JSON.net, follow the 2 ways that i found to register the dependencies but all way get me to an InvalidOperationException with a message "Something went wrong when trying to satisfy one of the dependencies during composition, make sure that you've registered all new dependencies in the container and inspect the innerexception for more details." with an inner exection of {"Unable to resolve type: Nancy.NancyEngine"}.
I'm using self hosting to run nancy and jeep everything really simple to been able just to test.
public static void Main(string[] args)
{
try
{
var host = new NancyHost(new Uri("http://localhost:8888/"));
host.Start(); // start hosting
Console.ReadKey();
host.Stop(); // stop hosting
}
catch
{
throw;
}
}
First I create a customSerializer
public class CustomJsonSerializer : JsonSerializer
{
public CustomJsonSerializer()
{
ContractResolver = new CamelCasePropertyNamesContractResolver();
Formatting = Formatting.Indented;
}
}
and then i tried 2 ways of registering
Using IRegistrations:
public class JsonRegistration : IRegistrations
{
public IEnumerable<TypeRegistration> TypeRegistrations
{
get
{
yield return new TypeRegistration(typeof(JsonSerializer), typeof(CustomJsonSerializer));
}
}
public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; protected set; }
public IEnumerable<InstanceRegistration> InstanceRegistrations { get; protected set; }
}
And also using Bootstrapper
public class NancyBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
container.Register<JsonSerializer, CustomJsonSerializer>();
}
}
Which means that when self hosting I add the custom bootstrapper
var host = new NancyHost(new Uri("http://localhost:8888/"), new NancyBootstrapper());
Both way return the same error.
Problem is actually the versions, the nancy json.net package is using Newton.Json 6.0.0.0, BUT when installing the package it will install automatically newer version that will create this problem. Not sure what has change in the Newton.JSON that will actually create this.
https://github.com/NancyFx/Nancy.Serialization.JsonNet/issues/27
Just to add my hard won knowledge in this area, after a greatly frustrating few hours using Nancy 1.4.1.
If you use a custom bootstrapper, make sure you make the call to base.ConfigureApplicationContainer(container); before you start your custom registrations.
So, not:
public class MyCustomBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
// MY BITS HERE...
base.ConfigureApplicationContainer(container);
}
}
but,
public class MyCustomBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container); // Must go first!!
// MY BITS HERE...
}
}
If you don't do this you will get the following error:
Something went wrong when trying to satisfy one of the dependencies
during composition, make sure that you've registered all new
dependencies in the container and inspect the innerexception for more
details.
with a helpful inner exception of:
Unable to resolve type: Nancy.NancyEngine
The solution of changing the order of these C# statements was actually alluded to in #StevenRobbins' excellent answer here (which I could have saved myself several hours of pain if I'd only read properly the first time).
Says Steven:
By calling "base" after you've made a manual registration you are
effectively copying over your original registration by autoregister.
Either don't call base, or call it before you do your manual
registrations.

Fail in calling Enable-Migrations for a generic DbContext class

Let's assume that I have this Entity Framework (v6.0) DbContext-based class, sitting in the "Food.Common" assembly:
public class FoodContext<T> : DbContext where T : Food<T>
{
public FoodContext() : base("MyConnectionString")
{
}
public DbSet<T> FoodElements { get; set; }
}
The above Food generic class is also sitting in the "Food.Common" assembly, and it is defined as:
public class Food<T> where T : Food<T>
{
// some code here...
public virtual T Copy()
{
// object copy goes here...
}
}
Also, I have this class which inherits from Food<T> and sits on the "Food.Extras" assembly:
public class HealthyFood : Food<HealthyFood>
{
// some code here...
public override HealthyFood Copy()
{
var baseCopy = base.Copy();
// extending the baseCopy with more data...
}
}
Now, I can easily instantiate and use the FoodContext<T> context like this:
using (var context = new FoodContext<HealthyFood>())
{
// some CRUD for "healthy food" goes here...
}
and the appropriate table is automatically created by EF in the database.
The problem is: when trying to call the "Enable-Migrations" command after updating the HealthyFood class (the model), I get notified by the Package Manager Console that "No context type was found in the assembly Food.Common".
My suspicion is that since the "Food.Common" does not contain a concrete (non generic) DbContext-based class, the "Enable-Migrations" thinks there's no context type inside this assembly at all.
So, how can I tell the Enable-Migrations that I want to update a concrete DbContext class (such as the FoodContext<HealthyFood>)?
Already tried Enable-Migrations -ContextTypeName Food.Common.FoodContext<HealthyFood> with no luck...

map hubs in referenced project

http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host
In my case, my hubs are in a project referenced from the project code that spins up the self-hosted application.
On the line connection.Start().Wait(); I get an exception. The following is the sequence of exceptions thrown at that line:
The specified registry key does not exist System.IO.IOException
'MessageHub' Hub could not be resolved InvalidOperationException
The remote server returned an error: (500) Internal Server Error WebException
The signature of the message hub class in the referenced project is public class MessageHub : Hub.
Update: To test the theory, I moved the hub class from the referenced project into my test project and updated the namespace. It worked. So I think the theory here is sound... default hub resolution does not find hubs in referenced project or in separate namespace.
How can I convince MapHubs to find the test hub in the referenced project?
I think that I have found an answer to this.
After doing some digging around the source code it seems that SignalR uses the following method to designate an IAssemblyLocator to locate Hubs.
internal static RouteBase MapHubs(this RouteCollection routes, string name, string path, HubConfiguration configuration, Action<IAppBuilder> build)
{
var locator = new Lazy<IAssemblyLocator>(() => new BuildManagerAssemblyLocator());
configuration.Resolver.Register(typeof(IAssemblyLocator), () => locator.Value);
InitializeProtectedData(configuration);
return routes.MapOwinPath(name, path, map =>
{
build(map);
map.MapHubs(String.Empty, configuration);
});
}
public class BuildManagerAssemblyLocator : DefaultAssemblyLocator
{
public override IList<Assembly> GetAssemblies()
{
return BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();
}
}
public class DefaultAssemblyLocator : IAssemblyLocator
{
public virtual IList<Assembly> GetAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies();
}
}
This got me to try to simply add my external assembly to current domain because although it was referenced it was not being loaded.
So before calling WebApp.Start I call the following line.
static void Main(string[] args)
{
string url = "http://localhost:8080";
// Add this line
AppDomain.CurrentDomain.Load(typeof(Core.Chat).Assembly.FullName);
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
Where Core.Chat is simply the Hub class I'm using.
And then the hubs defined in referenced assembly are loaded.
There might be a more straight forward way to go about this but I could not find anything in the documentation.
Hope this helps.

Resources