PostgreSQL + Npgsql connector + MVC and SimpleMembership Not working - postgresql

I've test the db connection without Websecurity and it works. I've followed the tutorial from Brice Lambson http://brice-lambson.blogspot.com.es/2012/10/entity-framework-on-postgresql.html
But when I use
WebSecurity.InitializeDatabaseConnection("myContext",
"UserProfile", "UserId", "UserName", autoCreateTables: false);
I get this exception:
System.InvalidOperationException was caught
HResult=-2146233079
Message=No user table found that has the name "UserProfile".
Source=WebMatrix.WebData
StackTrace:
in WebMatrix.WebData.SimpleMembershipProvider.ValidateUserTable()
in WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables)
in WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables)
in WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables)
in Glink.Filters.InitializeSimpleMembershipAttribute.SimpleMembershipInitializer..ctor() en c:\Users\...\InitializeSimpleMembershipAttribute.cs:line 46
InnerException: Npgsql.NpgsqlException
HResult=-2147467259
Message=ERROR: 42601: Syntax error near «[»
Source=Npgsql
ErrorCode=-2147467259
BaseMessage=Syntax error near «[»
Code=42601
Detail=""
ErrorSql=SELECT [UserId] FROM [UserProfile] WHERE (UPPER([UserName]) = ((E'Z')))
File=src\backend\parser\scan.l
Hint=""
Line=1002
Position=8
Routine=scanner_yyerror
Severity=ERROR
Where=""
StackTrace:
in Npgsql.NpgsqlState.<ProcessBackendResponses_Ver_3>d__a.MoveNext()
in Npgsql.ForwardsOnlyDataReader.GetNextResponseObject()
in Npgsql.ForwardsOnlyDataReader.GetNextRowDescription()
in Npgsql.ForwardsOnlyDataReader.NextResult()
in Npgsql.ForwardsOnlyDataReader..ctor(IEnumerable`1 dataEnumeration, CommandBehavior behavior, NpgsqlCommand command, NotificationThreadBlock threadBlock, Boolean synchOnReadError)
in Npgsql.NpgsqlCommand.GetReader(CommandBehavior cb)
in Npgsql.NpgsqlCommand.ExecuteScalar()
in WebMatrix.Data.Database.QueryValue(String commandText, Object[] args)
in WebMatrix.WebData.DatabaseWrapper.QueryValue(String commandText, Object[] parameters)
in WebMatrix.WebData.SimpleMembershipProvider.GetUserId(IDatabase db, String userTableName, String userNameColumn, String userIdColumn, String userName)
in WebMatrix.WebData.SimpleMembershipProvider.ValidateUserTable()
InnerException:
I guess that NpgSql could not be prepared to work with SimpleMerbership, but I'd like to know if any of you had tried this.
Thank you!!

You should try Daniel Nauck's AspSQLProvider: http://dev.nauck-it.de/projects/show/aspsqlprovider
It is a PostgreSQL implementation of the ASP.NET 2.0+ Membership, Role, Profile and Session-State Store Provider.
I hope it helps.

I'd hint you to try changing "autoCreateTables: false" to "autoCreateTables: true".

Doesn't work with postgres because it injects brackets ([ ... ]) into throughout the embedded SQL:
https://github.com/aspnetwebstack/aspnetwebstack/blob/master/src/WebMatrix.WebData/SimpleMembershipProvider.cs

Related

spring boot + spring data jpa #query invaild

spring boot 2.0
spring data jpa 2
#Modifying
#Query(name = "delete from User a where age=?1 and username=?1")
void deleteByAge(int i);
#Query is invalid. Did not execute the JPQL I wrote
question 2:
#Modifying
#Query(name = "delete from User a where age=?1 and username=?1")
void dByAge(int i);
spring boot startup exception:
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Failed to create query for method
public abstract void
com.unuobi.testboot.repository.UserRepository.dByAge(int)! No property
dByAge found for type User!
✔ #Query(value="select ....")
✖ #Query(name="select ....")
must be value ,
Use this as JPQL Query required age and username so both has to pass in your method , whatever type username is and they should be always in sequence they used in #Query:
#Modifying
#Query("delete from User a where age=?1 and username=?1")
void deleteByAge(int age, String username);
Or named query can be:
void deleteByAgeAndUsername(int age, String username);
make sure you have age and username in User entity.

How to solve entity framework core System.ArgumentNullException

From the following stacktrace, I can't tell what is wrong by the error message. I ran the migration command with --verbose flag hoping it would help pinpoint the issue but zilch.
dotnet ef migrations add migwl3 --verbose
I can't find a parameter named key
System.ArgumentNullException: Value cannot be null.
Parameter name: key
at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerMetadataExtensions.SqlServer(IKey key)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer. <Add>d__41.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__35`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer. <Add>d__29.MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer. <DiffCollection>d__56`1.MoveNext()
at System.Linq.Enumerable.ConcatIterator`1.MoveNext()
at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.S ort(IEnumerable`1 operations, DiffContext diffContext)
at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.Scaf foldMigration(String migrationName, String rootNamespace, String subNamespace)
at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMig ration(String name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(S tring name, String outputDir, String contextType)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Exec ute(Action action)
Value cannot be null.
Parameter name: key
Any tips on how to zero in on the issue (the project compiles fine) would be greatly appreciated
This is one of the first results from searching for Microsoft.EntityFrameworkCore.Utilities.Check.NotNull, so I'll add my stupid mistake:
I refactored a class to a different DatabaseContext, and was then calling Join between two IQueryable queries from those different contexts-- Obviously you can't do that in EntityFramework
I think Your Problem is Your Model that you not decoration [Key] attribute Or
Not use HasKey.
please share your code.
make sure that you wrote the Interface name in the constructor not the repository name.
example program
private IReviewRepository _reviewRepository;
private IPokemonRepository _pokemonRepository;
private readonly IReviewerRepository _reviewerRepository;
private IMapper _mapper;
public ReviewController(IReviewRepository reviewRepository,
IMapper mapper,
IPokemonRepository pokemonRepository,
IReviewerRepository reviewerRepository)
{
_reviewRepository = reviewRepository;
_pokemonRepository = pokemonRepository;
_reviewerRepository = reviewerRepository;
_mapper = mapper;
}
ReviewRepository instead of IReviewRepository
ReviewerRepository instead of IReviewerRepository
PokemonRepository instead of IPokemonRepository

EF 5 code first - using a method to determine the connection

Is it possible that the connection string is redirected to a method (instead using App.config)?
(App.config is not an option because the location for a sdf can be changed)
My connection string (sdf) can change via an OpenFileDialog for instance.
The hint concerning SQLExpress was seen.
When debugging, the migration goes towards the IMigrationMetadata.Id.
Then, DataException - An exception occurred while initializing the database.
at
System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
ProviderIncompatibleException - The provider did not return a ProviderManifestToken string.
{"An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. "}
at System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection)
The default ctor applies a connection string that cannot be used:
Data Source=.\SQLEXPRESS;Initial Catalog=Namespace.AbacusContext;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFrameworkMUE
But when invoking
this.Database.Initialize( false ); //good connStr applied
within a ctor (incl. arguments), then the default ctor is automatically invoked (but not by me) and that uses an impaired connection string. See overview:
public AbacusContext( DbConnection connection, bool contextOwnsConnection ) :
base( connection, contextOwnsConnection )
{
Database.SetInitializer( new MigrateDatabaseToLatestVersion<AbacusContext, Configuration>() );
string goodConnStr = this.Database.Connection.ConnectionString;//was used for a breakpoint
this.Database.Initialize( false );
}
public AbacusContext()
{
string badConnStr = this.Database.Connection.ConnectionString;
//SQLExpress and some other stuff can be seen now
}

Spring JDBC - Last inserted id

I'm using Spring JDBC. Is a simple way to get last inserted ID using Spring Framework or i need to use some JDBC tricks ?
jdbcTemplate.update("insert into test (name) values(?)", params, types);
// last inserted id ...
I found something like below, but i get: org.postgresql.util.PSQLException: Returning autogenerated keys is not supported.
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(
Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("insert into test (name) values(?)", new String[] {"id"});
ps.setString(1, "test");
return ps;
}
}, keyHolder);
lastId = (Long) keyHolder.getKey();
The old/standard way is to use call currval() after the insert (ref). Simple and secure.
Support for "generated keys for PreparedStatements" started only since PostgreSql Ver 8.4-701.

PayPal's CallerServices Works on localhost but not server

My PayPal Direct script works perfect on my machine. Both nUnit tests and via a website on localhost. However this first line of code fails on my server and another server. (both full trust)
CallerServices caller = new CallerServices();
Message: The type initializer for 'com.paypal.sdk.core.soap.SOAPAPICaller' threw an exception.
Source: paypal_base
Stack Trace:
at com.paypal.sdk.core.soap.SOAPAPICaller..ctor()
at com.paypal.sdk.services.CallerServices..ctor()
at TS.Common.BusinessLogic.PaymentGateways.PayPalProController.CChargeCard(String paymentAmount, Order CurrentOrder, String creditCardType, String creditCardNumber, String CVV2, String expMonth, String expYear, PaymentActionCodeType paymentAction, Transaction& transaction)
at TS.Common.BusinessLogic.PaymentGateways.PayPalProController.ChargeCard(Order CurrentOrder, Decimal Amount, String CreditCardNum, String ExpMonth, String ExpYear, String SecurityNumber, Transaction& transaction)
at OrderController.SubmitCreditCardPayment(Order order, Decimal ChargeAmount, String CreditCardNum, String ExpMonth, String ExpYear, String Var, String CardType, Transaction& transaction)
at OrderController.SubmitOrder(Order order, Transaction& transaction, Nullable`1 GiftCertId, String CreditCardNum, String ExpMonth, String ExpYear, String Var, String CardType, String Culture)
at Checkout.btnOrder_Click(Object sender, EventArgs e) in d:\Inetpub\tickets\Checkout.aspx.cs:line 488
Add log4net.dll , if not put it in your bin folder and add reference. It works for me...
Add the reference to the log4net.dll with the specific version only. It will work