We have a EF 6 Dbcontext and migrations in the separate class library project (data layer), rather than in the main mvc 6 project.
However, when we are trying to call this on the first run of the project
context.Database.Initialize(false);
We get very strange error message
System.IO.FileNotFoundException Could not find file
'MyProject.Data.resources'.
Stack Trace:
at System.Reflection.RuntimeAssembly.InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, Boolean throwOnFileNotFound, StackCrawlMark& stackMark)
at System.Resources.ManifestBasedResourceGroveler.GetSatelliteAssembly(CultureInfo lookForCulture, StackCrawlMark& stackMark)
at System.Resources.ManifestBasedResourceGroveler.GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, Boolean tryParents, Boolean createIfNotExists, StackCrawlMark& stackMark)
at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo requestedCulture, Boolean createIfNotExists, Boolean tryParents, StackCrawlMark& stackMark)
at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents)
at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
at System.Resources.ResourceManager.GetString(String name)
at System.Data.Entity.Migrations.DbMigrator.GetDefaultSchema(DbMigration migration)
at System.Data.Entity.Migrations.DbMigrator.<GetHistorySchemas>b__6(<>f__AnonymousType10<String, DbMigration> <>h__TransparentIdentifier4)
at System.Linq.Enumerable.<>c__DisplayClass7_0<TSource, TMiddle, TResult>.<CombineSelectors>b__0(TSource x)
at System.Linq.Enumerable.WhereSelectListIterator<TSource, TResult>.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__58<TSource>.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__58<TSource>.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__63<TSource>.MoveNext()
at System.Linq.Buffer<TElement>..ctor(IEnumerable<TElement> source)
at System.Linq.Enumerable.<ReverseIterator>d__74<TSource>.MoveNext()
at System.Data.Entity.Migrations.History.HistoryRepository.QueryExists(String contextKey)
at System.Data.Entity.Migrations.History.HistoryRepository.Exists(String contextKey)
at System.Data.Entity.Migrations.History.HistoryRepository.<GetUpgradeOperations>d__16.MoveNext()
at System.Linq.Enumerable.Any<TSource>(IEnumerable<TSource> source)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update()
at System.Data.Entity.MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration>.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf<TContext>.<CreateInitializationAction>b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction<TInput>.PerformAction(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action<InternalContext> action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Database.Initialize(Boolean force)
at MyProject.Data.DbHelper.SetupDatabase() in E:\Projects\MyProject\src\MyProject.Data\DbHelper.cs:line 29
at MyProject.Business.Services.DatabaseService.SetupDatabase() in E:\Projects\MyProject\src\MyProject.Business\Services\DatabaseService.cs:line 17
at MyProject.Web.Startup.ConfigureServices(IServiceCollection services) in E:\Projects\MyProject\src\MyProject.Web\Startup.cs:line 61
That's very strange. It works when we are trying to set connection string in the Data project's App.config and run update-database from package manager console (but I believe that's because in that case it behaves like a separate project).
Anyone have a good solution to this problem?
P.S. The other issues are not answering to this, because it is a problem with accessing migration in csproj project from xproj project.
It's a knowned dnx issue. It's not a migration problem, but a problem about EF6 model in class libraries.
Answer is here : Entity Framework 7 error : "EntityFramework.Core.resources" is missing (7.0.0-rc1-final)
Add this to your Startup's Configure method :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
var localizationOptions = new RequestLocalizationOptions()
{
SupportedCultures = new List<CultureInfo> { new CultureInfo("") },
SupportedUICultures = new List<CultureInfo> { new CultureInfo("") }
};
var invariantCulture = new RequestCulture(new CultureInfo(""), new CultureInfo(""));
app.UseRequestLocalization(localizationOptions, invariantCulture);
//...
}
Related
I am trying to instantiate a class from DemoClass.dll using Activator.CreateInstance(type.Assembly.FullName, type.FullName)
This class implements the one interface from other dll. Lets say DemoInterfaces.dll. Earlier it was supposed to implement two methods. But now we have only one method i.e. one is removed. However, while instantiating it is trying to reference old copy which I don't see anywhere. It is the new dll and also checked it in dotpeek. The DemoInterfaces.dll interface has only one method.
Below is the sample code.
Assembly assembly = Assembly.LoadFrom(path);
Type type = assembly.GetType("className", true, true);
var xxx = Activator.CreateInstance(type.Assembly.FullName, type.FullName);
However, it is looking the implementation of second method. So Method implementation in class from DemoClass.dll is not found.
{"Exception has been thrown by the target of an invocation."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146232828
HelpLink: null
InnerException: {"Method not found: ''xxxx"}
Message: "Exception has been thrown by the target of an invocation."
Source: "mscorlib"
StackTrace: " at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)\r\n at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(Type type, Boolean nonPublic)\r\n at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)\r\n at System.Activator.CreateInstance(String assemblyString, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Bi
nder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)\r\n at System.Activator.CreateInstance(String assemblyName, String typeName)\r\n at xxxx in xx"
TargetSite: {System.Object CreateInstance(System.RuntimeType, Boolean, Boolean, Boolean ByRef, System.RuntimeMethodHandleInternal ByRef, Boolean ByRef)}
Any help is highly appreciated.
Try passing Type only.
Assembly assembly = Assembly.LoadFrom(path);
Type type = assembly.GetType("Namespace.className");
object instance = Activator.CreateInstance(type);
I am working on enqueue jobs using hangfire in my application.
my enqueue job statement is given below,
string jobId = BackgroundJob.Enqueue(() =>
strategy.get(typeof(_service.Engine.Summary), cpdata));
when this will enqueue my job successfully but got the error message in State table like this,
"FailedAt": "2018-03-21T13:14:46.0172303Z", "ExceptionType":
"System.MissingMethodException", "ExceptionMessage": "No
parameterless constructor defined for this object.",
"ExceptionDetails": "System.MissingMethodException: No parameterless
constructor defined for this object.\r\n at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)\r\n
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n at
System.Activator.CreateInstance(Type type, Boolean nonPublic)\r\n at
System.Activator.CreateInstance(Type type)\r\n at
Hangfire.JobActivator.SimpleJobActivatorScope.Resolve(Type type)\r\n
at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext
context)\r\n at
Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_0.b__0()\r\n
at
Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter
filter, PerformingContext preContext, Func 1 continuation)\r\n at
Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext
context, IEnumerable`1 filters)\r\n at
Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext
context)\r\n at
Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context,
IStorageConnection connection, String jobId)"
Is this DI issue that creating this type of error?
i used calling method in Enqueue using the reference of this link
Factory method with DI and IOC
For Example,
var strategy = new CarStrategy(new ICarFactory[] {
new Car1Factory(dep1, dep2, dep3),
new Car2Factory(dep4, dep5, dep6),
new Car3Factory(dep7, dep8, dep9)
});
My Code is Like this,
var strategy = new Strategy(new ICP[] {
new _Services.Engine.Detail.Detail(),
new _1Services.Engine.Summary.Summary(),
});
var CP = PrepareCPModelForEngine(c);
string jobId = BackgroundJob.Enqueue(() =>
strategy.get(typeof(_Services.Engine.Summary.Summary), cp));
I'm trying to use Hangfire in my application to fetch( from external APIs) currency conversion rates on a daily basis and insert in application database.
Successfully configured ( think so ) and the Hangfire Tables are created in the DB and the Job table is having entries but the Job is not successfully executed and while checking the State Table it shows failed and have an error message like
{"FailedAt":"2017-10-12T07:55:00.3075439Z",
"ExceptionType":"System.MissingMethodException",
"ExceptionMessage":"Cannot create an instance of an interface.",
"ExceptionDetails":"System.MissingMethodException: Cannot create an instance of an interface.\r\n
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)\r\n
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)\r\n
at System.Activator.CreateInstance(Type type, Boolean nonPublic)\r\n at System.Activator.CreateInstance(Type type)\r\n at Hangfire.JobActivator.ActivateJob(Type jobType)\r\n
at Hangfire.JobActivator.SimpleJobActivatorScope.Resolve(Type type)\r\n at Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext context)\r\n
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_0.<PerformJobWithFilters>b__0()\r\n
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter filter, PerformingContext preContext, Func`1 continuation)\r\n
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass8_1.<PerformJobWithFilters>b__2()\r\n
at Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext context, IEnumerable`1 filters)\r\n
at Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)\r\n
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context, IStorageConnection connection, String jobId)"}
Code used :
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
GlobalConfiguration.Configuration.UseSqlServerStorage("ERPContext");
RecurringJob.AddOrUpdate<IAPIRequest>(x => x.ProcessCurrencyConversion(), Cron.MinuteInterval(1));
app.UseHangfireDashboard();
app.UseHangfireServer();
}
}
Interface and Class which has the Method to executed
public interface IAPIRequest
{
void ProcessCurrencyConversion();
}
public class APIRequest : IAPIRequest
{
public void ProcessCurrencyConversion()
{
WebClient client = new WebClient();
string urlPattern = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDKWD,EURKWD,GBPKWD,AEDKWD,ZARKWD%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var jsonResult = client.DownloadString(urlPattern);
dynamic results = JsonConvert.DeserializeObject<dynamic>(jsonResult);
var rates = results.rate;
List<CurrencyJSON> currencies = new List<CurrencyJSON>();
using (var db = new ERPContext())
{
foreach (var rate in rates)
{
var currencyJson = new CurrencyJSON();//POCO
currencyJson.Bid = rate.Bid;
currencyJson.Name = rate.Name;
currencies.Add(currencyJson);
}
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.ValidateOnSaveEnabled = false;
db.CurrencyJson.ToList().AddRange(currencies);
db.SaveChanges();
}
}
}
What am I doing wrong?
Appreciate any help , Thanks in advance .
Have already checked similar question posted here but didn't help .
As #Diado pointed out in the comments, HangFire needs a IoC if using an Interface as there is no default support. Or you can use the Class directly instead of an interface.
https://github.com/devmondo/HangFire.SimpleInjector is one of the IoC injector which I used .
We just updated hangfire from 1.3.4 to 1.5.3.
Our startup has changed from this:
private static void DoHangfire(IAppBuilder app)
{
var options = new BackgroundJobServerOptions
{
// Set thread count to 1
WorkerCount = 1
};
app.UseHangfire(config =>
{
config.UseSqlServerStorage(ConfigurationManager.ConnectionStrings["JobsDB"].ConnectionString);
config.UseAuthorizationFilters(new HangfireDashboardAuthorizationFilter());
config.UseServer(options);
});
// Set retries to zero
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
JobActivator.Current = new WindsorJobActivator(Container.Kernel);
}
to this:
private static void DoHangfire(IAppBuilder app)
{
var options = new BackgroundJobServerOptions
{
// Set thread count to 1
WorkerCount = 1
};
GlobalConfiguration.Configuration.UseSqlServerStorage(
ConfigurationManager.ConnectionStrings["JobsDB"].ConnectionString);
app.UseHangfireDashboard("/hangfire", new DashboardOptions()
{
AuthorizationFilters = new List<IAuthorizationFilter>
{
new HangfireDashboardAuthorizationFilter()
}
});
app.UseHangfireServer(options);
// Set retries to zero
GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute { Attempts = 0 });
JobActivator.Current = new WindsorJobActivator(Container.Kernel);
}
Now all our jobs (we have 4 different kinds of jobs) fail immediately with this error:
System.MissingMethodException: No parameterless constructor defined
for this object. at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic) at
System.Activator.CreateInstance(Type type) at
Hangfire.JobActivator.SimpleJobActivatorScope.Resolve(Type type) at
Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext
context) at
Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass3.b__0()
at
Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter
filter, PerformingContext preContext, Func1 continuation) at
Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext
context, IEnumerable1 filters) at
Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context,
IStorageConnection connection, String jobId)
Well the problem had to do with some magic in how the new version of Hangfire interacted with the Hangfire.Windsor package, which simply provides a custom JobActivator with a windsor container for service location.
By moving the
JobActivator.Current = new WindsorJobActivator(Container.Kernel);
above the call to app.UseHangfireServer() we were able to uncover the real exception message, which was a Castle.MicroKernel.ComponentNotFoundException informing us that it couldn't wire in the dependency containing the method we wanted hangfire to run.
Suffice to say, in 1.3.4, to run a job you can do this:
BackgroundJob.Enqueue(() => thingWhichDoesStuff.DoStuff());
where thingWhichDoesStuff is injected into the containing class and the hangfire.windsor JobActivator is just magically able to resolve to the type.
However in 1.5.3 this magic resolution no longer happens, so you must explicitly tell the JobActivator the interface of the type containing the method you want hangfire to run:
BackgroundJob.Enqueue<IDoStuff>(x => x.DoStuff());
This causes all our jobs to start working again.
Hi i am developing MMC snap in C#,
in this i want to read XML file so where to put my xml file.
the code is not giving any build error but when i am adding the snapin in MMC its giveing error what to do.
[SnapInSettings("{2078B103-76FF-46E1-95BB-8B2CE3A72E60}",
DisplayName = "Configuration",
Description = "abc Pvt Ltd.")
]
public class Mymmc : SnapIn
{
XDocument xDoc;
public Sararmmc()
{
ScopeNode childscopenode;
xDoc = XDocument.Load("MMCSnapinXML.xml");
IEnumerable<XElement> xelements = xDoc.Root.Descendants();
this.RootNode = new ScopeNode();
this.RootNode.DisplayName = xDoc.Root.Attribute("name").Value;
foreach (XElement elm in xelements)
{
childscopenode = new ScopeNode();
childscopenode.DisplayName = elm.Attribute("name").Value;
this.RootNode.Children.Add(childscopenode);
}
}
}
i am getting
Exception has been thrown by the target of an invocation.
Server stack trace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(String assemblyName, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstance(String assemblyName, String typeName)
at System.AppDomain.CreateInstanceAndUnwrap(String assemblyName, String typeName)
at Microsoft.ManagementConsole.Internal.SnapInClient.CreateSnapIn(String assemblyName, String typeName)
at Microsoft.ManagementConsole.Internal.ClassLibraryServices.Microsoft.ManagementConsole.Internal.IClassLibraryServices.CreateSnapIn(String assemblyName, String typeName)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
Exception rethrown at [0]:
at Microsoft.ManagementConsole.Executive.SnapInInitializationOperation.OnStart()
at Microsoft.ManagementConsole.Executive.Operation.Start()
at Microsoft.ManagementConsole.Executive.RunningOperationsTable.EnqueueOperation(Operation operation)
at Microsoft.ManagementConsole.Executive.StandAloneComponentData..ctor(SnapInRegistrationInfo info, Int32 bookkeepingId)
at Microsoft.ManagementConsole.Advanced.FrameworkSnapInFactory.Microsoft.ManagementConsole.Advanced.ISnapInFactory.CreateSnapIn(Int32 bookkeepingId, String snapInKey, Object& snapIn)
There are many exceptions which could be thrown in your constructor (the stack trace indicates that this is the source of the error). It could be a malformed XML exception is thrown on XDocument.Load, it could also be null reference exception if any of the named nodes/attributes you're accessing don't exist. It could be a file not found exception, or even a SecurityException - it could even be something more obscure such as MMC requiring that your assembly is signed.. without knowing what type of exception you're getting it's very difficult for anyone to help you!
As I said in my comment, when you receive errors at runtime that you can't easily explain - this is when having verbose logging in your application becomes really valuable! NLog and log4net are the two most popular logging frameworks for .NET applications