JetEntityFrameworkProvider setup in VS2017 - jet-ef-provider

After compiling my project in VS2017 15.9.21 for.NET 4.5, I got following error, what am I missing?
Unable to determine the provider name for provider factory of type 'JetEntityFrameworkProvider.JetProviderFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
Error Dialog
This is where the exception gets thrown:
JetConnection.ShowSqlStatements = True
Dim fac1 = New JetConnectionFactory()
Dim con1 = fac1.CreateConnection(ORMGlobal.ConnectionString)
Using db As ORM = New ORM(con1)
Dim model = db.People.Count()
' ...
End Using
This is my DbContext setup:
Partial Public Class ORM
Inherits DbContext
Public Sub New()
MyBase.New()
Database.SetInitializer(New NullDatabaseInitializer(Of ORM))
End Sub
Public Sub New(con As Common.DbConnection)
MyBase.New(con, True)
Database.SetInitializer(New NullDatabaseInitializer(Of ORM))
End Sub
' ...
End Class
This is my config.app
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<entityFramework>
<providers>
<provider invariantName="JetEntityFrameworkProvider" type="JetEntityFrameworkProvider.JetProviderServices, JetEntityFrameworkProvider" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="JetEntityFrameworkProvider"/>
<add invariant="JetEntityFrameworkProvider" name="Jet Entity Framework Provider" description="Jet Entity Framework Provider"
type="JetEntityFrameworkProvider.JetProviderFactory, JetEntityFrameworkProvider"/>
</DbProviderFactories>
</system.data>
</configuration>
Exception details:
Exception thrown: 'System.NotSupportedException' in EntityFramework.dll
5/20/2021 3:49:07 PM :dwl: :LV:: Error in ConnectToDSN: System.NotSupportedException: Unable to determine the provider name for provider factory of type 'JetEntityFrameworkProvider.JetProviderFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
at System.Data.Entity.Utilities.DbProviderFactoryExtensions.GetProviderInvariantName(DbProviderFactory factory)
at System.Data.Entity.Infrastructure.DependencyResolution.DefaultInvariantNameResolver.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.CachingDependencyResolver.<>c__DisplayClass4_0.<GetService>b__0(Tuple`2 k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.Infrastructure.DependencyResolution.CachingDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.<>c__DisplayClass5_0.<GetService>b__0(IDbDependencyResolver r)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.RootDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.<>c__DisplayClass5_0.<GetService>b__0(IDbDependencyResolver r)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver`2.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver, Object key)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInvariantName(DbConnection connection)
at System.Data.Entity.Internal.InternalConnection.get_ProviderName()
at System.Data.Entity.Internal.LazyInternalContext.get_ProviderName()
at System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at TheBoardRoom.LockView.SQLdbHandler.ConnectToDSN(String sConnDSN, ADOConnection& connDB)

Related

Exception has been thrown by the target of an invocation in asp.net core and postgresql migration

I am trying to create a project. That's why I downloaded a startup template from this link. Then I tried to configure with asp.net core. I set the connection string as "Default": "User ID=postgres;Password=**********;Host=localhost;Port=5432;Database=LibraryManagementDb;Pooling=true;". and then changed UseSqlServer to UseNpgsql in LibraryManagementDbContextConfigurer class.
`
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, string connectionString)
{
builder.UseNpgsql(connectionString);
}
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, DbConnection connection)
{
builder.UseNpgsql(connection);
}
`
and add the below code to DbContext class
`
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(p => p.Value)
.HasMaxLength(100); // any integer that is smaller than 10485760
}
`
and removed all migration classes from the Migration folder and run add-migration Initial_Migration command in the package manager console
but I got the Exception has been thrown by the target of an invocation. error
this is the whole exception
`
PM> add-migration Initial_Migration
Build started...
Build succeeded.
System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.TypeLoadException: Method 'get_Info' in type
'Microsoft.EntityFrameworkCore.Infrastructure.
Internal.NpgsqlOptionsExt
ension' from assembly 'Npgsql.EntityFrameworkCore.PostgreSQL,
Version=2.1.0.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'
does not have an implementation.
at Microsoft.EntityFrameworkCore
.NpgsqlDbContextOptionsExtensions.UseNpgsql[TContext]
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextConfigurer
.Configure(DbContextOptionsBuilder`1 builder, String
connectionString) in D:\6.0.0\aspnet-
core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextConfigurer.cs:line
10
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextFactory.CreateDbContext(String[] args)
in D:\6.0.0\aspnet-core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextFactory.cs:line 17
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor, Boolean
wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters)
at Microsoft.EntityFrameworkCore.Design
.Internal.DbContextOperations.CreateContextFromFactory(Type
factory,
Type contextType)
at
Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.
<>c__DisplayClass16_0.<FindContextFactory>b__1()
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal
.MigrationsOperations.AddMigration(String name, String outputDir,
String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigrationImpl(String name, String outputDir, String
contextType,
String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.Execute(Action action)
Exception has been thrown by the target of an invocation.
`
How can I resolve this??? Please help...
By updating 'Npgsql.EntityFrameworkCore.PostgreSQL' solved this problem

MembershipProvider change connection string in code

I am trying to implement Asp.net Forms Authentication in my site. Usually, you provide the name of your DB connection string in your web.config. However, as our database setup is a little more complicated, I was looking for a way to manually provide the MembershipProvider the connection string in code.
Thanks!
You don't have to use a connectionStringName for SqlMembershipProvider, instead you can supply the connection string directly. I.e. instead of:
<membership defaultProvider="SqlProvider" ...>
<providers>
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="MyConnectionStringName"
.../>
</providers>
</membership>
You can specify the connection string directly as:
<membership defaultProvider="SqlProvider" ...>
<providers>
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider"
connectionString="data source=... "
.../>
</providers>
</membership>
Therefore you could also derive a custom provider from SqlMembershipProvider, and build the connection string dynamically as follows:
public class MySqlMembershipProvider : SqlMembershipProvider
{
public override void Initialize(string name, NameValueCollection config)
{
config["connectionString"] = BuildMyCustomConnectionString();
base.Initialize(name, config);
}
}
I came across this needing to do the same thing, set the connection string via code and not in the web.config, although I needed to change more than the name, I needed the actual value to be dynamically generated. If you want to change the actual connection string to be generated from code you can do the following:
web.config
...
<connectionStrings>
<add name="ConnectionPlaceHolder" connectionString="This is a place holder"/>
</connectionStrings>
...
<roleManager defaultProvider="SqlRoleProvider" enabled="true">
<providers>
<clear/>
<add name="SqlRoleProvider" type="MyClassLibraries.Web.Security.MyCustomSqlRoleProvider" connectionStringName="ConnectionPlaceHolder" applicationName="MyApplicationName"/>
</providers>
</roleManager>
Provider Class
public class MySqlRoleProvider : SqlRoleProvider
{
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
try
{
config["connectionStringName"] = "ConnectionPlaceHolder";
base.Initialize(name, config);
FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringField.SetValue(this, ApplicationConfiguration.RetrieveApplicationConfigurationValue(myConnectionString));
}
catch (Exception ex)
{
CurrentOperation.RaiseException(ex);
throw ex;
}
}
private string myConnectionString()
{
return "Server=MyServer;database=MyDB;uid=aspnetDBUser;pwd=myPassword"
}
}
When you call base.Initialize() the .NET class requires there be a name specified in the web.config which is why you have to put something, so I just used a placeholder since I knew I would be overriding it in the code.
Our team did this because we needed to dynamically build connection strings based on different environments and didn't want to have to worry about having multiple web.configs floating around.

How to add custom HTTP headers to asmx call using SoapExtension in c#

I am trying to add a custom HTTP header to the asmx call by intercepting it using the ProcessMessage (SoapMessage message) by extending SoapExtension Class in c#.
The problem here is that all i have in ProcessMessage() is the SoapMessage, while i need to add a custom http header.
I tried doing this :
HttpContext.Current.Request.Headers.Add("X-MyHeader", "xyz");
but it doesn't work.
I resolved this using the following steps:
Build an assembly using the class
namespace HttpWebRequestTest {
public class CustomHttpRequestCreator : IWebRequestCreate
public CustomHttpRequestCreator() { }
public WebRequest Create(Uri uri) {
HttpWebRequest webRequest = Activator.CreateInstance(typeof(HttpWebRequest),
BindingFlags.CreateInstance | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance,
null, new object[] { uri, null }, null) as HttpWebRequest;
webRequest.Headers.Add("MyHeader:MyValue");
return webRequest;
}
}
}
Add the file to GAC and register in web.config
<system.net>
<webRequestModules>
<remove prefix="http:"/>
<remove prefix="https:"/>
<add prefix="http:" type="HttpWebRequestTest.CustomHttpRequestCreator, HttpWebRequestTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2bc4ccb2cdedce53" />
<add prefix="https:" type="HttpWebRequestTest.CustomHttpRequestCreator, HttpWebRequestTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2bc4ccb2cdedce53" />
</webRequestModules>
</system.net>

Object reference error during custom session state provider initialization

I have written a custom session state provider which works fine in debug mode but once deployed on the server (IIS 6) i get the following error:
Event code: 3008
Event message: A configuration error has occurred.
Event time: 10/7/2011 3:05:02 PM
Event time (UTC): 10/7/2011 9:35:02 AM
Event ID: 00e2c8b1368b45608bb062eb2ba9d0db
Event sequence: 2
Event occurrence: 1
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1/Root/bizapp-1-129624536989844520
Trust level: Full
Application Virtual Path: ...
Application Path: ...
Machine name: ...
Process information:
Process ID: 7556
Process name: w3wp.exe
Account name: ...
Exception information:
Exception type: ConfigurationErrorsException
Exception message: Object reference not set to an instance of an object. (E:\Program Files\BizAPP\WebClient\web.config line 282)
Request information:
Request URL: http://localhost:8080/bizapp/login.aspx
Request path: /bizapp/login.aspx
User host address: 127.0.0.1
User:
Is authenticated: False
Authentication Type:
Thread account name: ...
Thread information:
Thread ID: 1
Thread account name: ...
Is impersonating: False
Stack trace: at System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType)
at System.Web.SessionState.SessionStateModule.InitCustomStore(SessionStateSection config)
at System.Web.SessionState.SessionStateModule.InitModuleFromConfig(HttpApplication app, SessionStateSection config)
at System.Web.SessionState.SessionStateModule.Init(HttpApplication app)
at System.Web.HttpApplication.InitModulesCommon()
at System.Web.HttpApplication.InitModules()
at System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
at System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context)
at System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context)
at System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
EDIT
line 282 is from web.config having the provider info, 3rd line below
<sessionState mode="Custom" customProvider="SessionStateStoreProvider" timeout="180">
<providers>
<add name="SessionStateStoreProvider" type="type full name" />
</providers>
</sessionState>
It means the "Object reference not set to an instance of an object" exception happens in one of your provider's methods (for example in the Initialize method). There's a bug in that code.
So you can either put a breakpoint in there and debug, or surround overridden methods with a try catch that can transform the exception in text, like this:
public class YourSessionState : SessionStateStoreProviderBase
{
public override void Initialize(string name, NameValueCollection config)
{
try
{
// your original Initialize code here
}
catch (Exception e)
{
throw new Exception("Error in initialize: " + e);
}
}
}
If you put the .PDB files aside the .DLL, you should now see the error line number.
You're not specifying the type correctly in your configuration.
Example:
<sessionState mode="Custom" customProvider="SessionStateStoreProvider">
<providers>
<add name="SessionStateStoreProvider"
type="Namespace.To.Your.SessionStateStoreClass" />
</providers>
</sessionState>
Unless you intentionally omitted the type.

ASP.NET MVC2 Error: No parameterless constructor defined for this object

Edit: This is fixed -- See Solution below
Solution: First I incorrectly had my node defined in /shared/web.config instead of the web.config in the root of the WebUI project. I also had not correctly defined my connection string within web.config. I have pasted the proper web.config sections below:
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
<!--more sectiongroup and sections redacted for brevity -->
</configSections>
<castle>
<components>
<component id="ProdsRepository" service="DomainModel.Abstract.IProductsRepository, DomainModel" type="DomainModel.Concrete.SqlProductsRepository, DomainModel">
<parameters>
<connectionString>Data Source=.\SQLExpress;Initial Catalog=SportsStore; Integrated Security=SSPI</connectionString>
</parameters>
</component>
</components>
</castle>
I also had to adjust the method body of WindsorControllerFactory.cs (IoC Container) to return null for invalid requests like so:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
else
return (IController)container.Resolve(controllerType);
}
End of Solution
I'm following the book Pro ASP.NET MVC2 by Sanderson. I've implemented the IoC container and gotten the web.config straightened out. When I attempt to run my application I get the error "No parameterless constructor defined for this object"
After some searching I found this exact issue on SO here. The solution is to create the constructor with no parameters but I'm having an issue doing this. I've pasted the code from ProductsController.cs below
namespace WebUI.Controllers
{
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
}
Above the public ProductsController that has parameters I tried doing:
public ProductsRepository() : this(new productsRepository())
{
}
I'm unclear about exactly what needs to go after the "new". IProductsRepository doesn't seem to work and neither does what I have written. I have pasted the stack trace below:
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
[InvalidOperationException: An error occurred when trying to create a controller of type 'WebUI.Controllers.ProductsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8682818
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Any help would be greatly appreciated.
Edit: Posting WindsorControllerFactory.cs code:
namespace WebUI
{
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
// The contructor:
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
public WindsorControllerFactory()
{
// Instantiate a container, taking config from web.config
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
// Also register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
container.AddComponentLifeStyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
}
Edit2: Pertinent Web.config nodes:
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="ProdsRepository"
service="DomainModel.Abstract.IproductsRepository, DomainModel"
type="DomainModel.Concrete.SqlProductsRepository, DomainModel"></component>
<parameters>
</parameters>
</components>
</castle>
You need to configure a custom controller factory in order to wire up your DI framework inside Application_Start method in global.asax. So for example if you are using Unity as DI framework you could:
ControllerBuilder.Current.SetControllerFactory(
typeof(UnityControllerFactory)
);
Check out this blog post for more information.
you can make use of setter based injection
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController()
{
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
public IProductsRepository MyRepository
{
get
{
return productsRepository;
}
set
{
productsRepository = value;
}
}
}
here , you need to manually set the MyRepository.
but best would be , if you register your repository to a container and beliving that you are using Unity framework , so you can do it by IUnityContainer.RegisterType() method

Resources