IdRepoPluginsCache.getAMRepoPlugin: Unable to instantiate plugin for Org: Error in OpenAm - openssh

I am trying to develop my own IDREPO:
My User Table is as follows:
(id,firstName,lastName,password,loginStatus.....)
My IDREpo implemented class has the following details:
private static final Set<IdType> SUPPORTED_TYPES;
static {
logger.debug("\nMethod - Static Supported Types");
SUPPORTED_TYPES = new HashSet<>();
SUPPORTED_TYPES.add(IdType.USER);
SUPPORTED_TYPES.add(IdType.GROUP);
}
private static final Set<IdOperation> SUPPORTED_OPS;
static {
logger.debug("\nMethod - Static Supported OPS");
SUPPORTED_OPS = new HashSet<>();
// DELETE and SERVICE are the other options
SUPPORTED_OPS.add(IdOperation.READ);
SUPPORTED_OPS.add(IdOperation.CREATE);
SUPPORTED_OPS.add(IdOperation.EDIT);
//SUPPORTED_OPS.add(IdOperation.SERVICE);
}
static {
logger.debug("\nMethod - Static PropertyNameRemapper. Loaded Properties: "
+ dbColumnProperties);
PROP_REMAPPER.setOpenSSOtoJDBC("lastName",
dbColumnProperties.getProperty("user.lastName"));
PROP_REMAPPER.setOpenSSOtoJDBC("id",
dbColumnProperties.getProperty("user.id"));
PROP_REMAPPER.setOpenSSOtoJDBC("password",
dbColumnProperties.getProperty("user.password"));
PROP_REMAPPER.setOpenSSOtoJDBC("firstName",
dbColumnProperties.getProperty("user.firstname"));
}
But when I debug my code I get the exception as :
getting exception:
java.lang.ClassCastException: JDBCIdRepo cannot be cast to com.sun.identity.idm.plugins.database.DaoInterface
at com.sun.identity.idm.plugins.database.DatabaseRepo.initialize(DatabaseRepo.java:275)
at com.sun.identity.idm.server.IdRepoPluginsCache.constructIdRepoPlugin(IdRepoPluginsCache.java:475)
at com.sun.identity.idm.server.IdRepoPluginsCache.addIdRepo(IdRepoPluginsCache.java:353)
at com.sun.identity.idm.server.IdRepoPluginsCache.removeIdRepo(IdRepoPluginsCache.java:251)
at com.sun.identity.idm.server.IdRepoPluginsCache.organizationConfigChanged(IdRepoPluginsCache.java:646)
at com.sun.identity.sm.ServiceConfigManagerImpl.notifyOrgConfigChange(ServiceConfigManagerImpl.java:488)
at com.sun.identity.sm.ServiceConfigManagerImpl.objectChanged(ServiceConfigManagerImpl.java:448)
at com.sun.identity.sm.SMSNotificationManager.sendNotifications(SMSNotificationManager.java:289)
at com.sun.identity.sm.SMSNotificationManager$LocalChangeNotifcationTask.run(SMSNotificationManager.java:365)
at com.iplanet.am.util.ThreadPool$WorkerThread.run(ThreadPool.java:306)

Related

java test custom annotation that load message from properties file

I have create custom annotation that load default error message from properties file
Java hibernate-validator #interface load from properties
now i want to test it, that when invalid value is fill, the default error is show up
here is my test class
public class CreditCardTest {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
String[] inValidValues = new String[] {
"??",
"##",
"]]]"
};
#Test
public void ccInValid() {
for (String value : inValidValues) {
AnnotatedBean bean = new AnnotatedBean();
bean.value = value;
Set<ConstraintViolation<AnnotatedBeanCustom>> constraintViolationCustom = validator.validate(bean);
constraintViolation.stream().forEach( v -> assertEquals(v.getMessage(), "contains invalid character"));
}
}
private class AnnotatedBean {
#AccountNumber
String value;
}
}
when i run above test class the error is like
org.junit.ComparisonFailure: expected:<[{pacakge.cc.message}]> but was:<[contains invalid character]>
how do make the annotation on test class load the properties file?

Spring R2DBC proper way to initialize database with postgres

I have the following code:
#Component
public class TemplateDatabaseLoader {
private Logger LOGGER = LoggerFactory.getLogger(TemplateDatabaseLoader.class);
#Bean
public CommandLineRunner demo(DatabaseClient databaseClient, ItemRepository itemRepository) {
return args -> {
databaseClient.execute(
"CREATE TABLE item (" +
"id SERIAL PRIMARY KEY," +
"name VARCHAR(255)," +
"price REAL" +
");"
).fetch().all().blockLast(Duration.ofSeconds(10));
itemRepository.save(new Item("Alf alarm clock", 19.99)).block();
LOGGER.debug("COMMAND LINE RUNNER");
itemRepository.save(new Item("Smurf TV tray", 24.99)).block();
};
}
}
And:
#SpringBootApplication
public class DemoApplication extends AbstractR2dbcConfiguration {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public ConnectionFactory connectionFactory() {
PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
.host("127.0.0.1")
.database("cart")
.username("cart")
.password("cart").build());
return connectionFactory;
}
#Bean(name={"r2dbcDatabaseClient"})
DatabaseClient databaseClient() {
return DatabaseClient.create(connectionFactory());
}
}
I get the following error:
Suppressed: java.lang.Exception: #block terminated with an error
Caused by: io.r2dbc.postgresql.ExceptionFactory$PostgresqlBadGrammarException: relation "item" already exists
And earlier on the errors:
Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.CannotGetJdbcConnectionException
If I modify my code to say:
CREATE TABLE IF NOT EXISTS item
Then I no longer get the error about the item relation existing, however, it seems the transaction gets cancelled entirely?
I get the following output:
2020-09-21 17:31:58.476 DEBUG 16639 --- [ restartedMain] com.example.demo.TemplateDatabaseLoader : COMMAND LINE RUNNER
2020-09-21 17:31:58.476 DEBUG 16639 --- [actor-tcp-nio-2] i.r.postgresql.util.FluxDiscardOnCancel : received cancel signal
So my questions are
What is the proper way to do this?
Why does my CommandLineRunner code seem to execute twice? The table does not persist after running the code, so it seems it must be executing twice to get the first error about the table existing.
Thank you.
I got it working. I added a new class to load the schema from a file:
#Configuration
public class InitializerConfiguration {
private Logger LOGGER = LoggerFactory.getLogger(InitializerConfiguration.class);
#Bean
public ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {
ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);
CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("schema.sql")));
initializer.setDatabasePopulator(populator);
return initializer;
}
}
This loads the schema.sql under resources. My TemplateDatabaseLoader now looks like this:
#Component
public class TemplateDatabaseLoader {
private Logger LOGGER = LoggerFactory.getLogger(TemplateDatabaseLoader.class);
#Bean
public CommandLineRunner demo(ItemRepository itemRepository) {
return args -> {
itemRepository.save(new Item("Alf alarm clock", 19.99)).block();
itemRepository.save(new Item("Smurf TV tray", 24.99)).block();
};
}
}
This loads the two items.

Tests fail with #Scheduled Task: JdbcSQLSyntaxErrorException Table "USER_ACCOUNT_CREATED_EVENT" not found

Summary & first problem
I am trying to test my user registration mechanism. When a new user account is created via my REST API, a UserAccountCreatedEvent is stored in the database. A scheduled task checks the database every 5 seconds for new UserAccountCreatedEvents and if one is present, sends an email to the registered user. When running my tests I encounter the problem that the table for the UserAccountCreatedEvent can't be found (see exception below). I used to send the email in a blocking manner in the service method, but I recently switched to this async approach. All my tests worked perfectly for the blocking approach and the only thing I changed for the async approach is to include Awaitility in the test.
2019-04-23 11:24:51.605 ERROR 7968 --- [taskScheduler-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task.
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select useraccoun0_.id as id1_0_, useraccoun0_.completed_at as complete2_0_, useraccoun0_.created_at as created_3_0_, useraccoun0_.in_process_since as in_proce4_0_, useraccoun0_.status as status5_0_, useraccoun0_.user_id as user_id1_35_ from user_account_created_event useraccoun0_ where useraccoun0_.status=? order by useraccoun0_.created_at asc limit ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException:
Table "USER_ACCOUNT_CREATED_EVENT" not found; SQL statement:
select useraccoun0_.id as id1_0_, useraccoun0_.completed_at as complete2_0_, useraccoun0_.created_at as created_3_0_, useraccoun0_.in_process_since as in_proce4_0_, useraccoun0_.status as status5_0_, useraccoun0_.user_id as user_id1_35_ from user_account_created_event useraccoun0_ where useraccoun0_.status=? order by useraccoun0_.created_at asc limit ? [42102-199]
Full stack trace
Second problem
As if that were not enough, the tests behave completely different when running them in debug mode. When I set a breakpoint in the method that is called by the method which is annotated with #Scheduled, it is invoked several times althogh #Scheduled is configured with a fixedDelayString (fixed delay) of 5000ms. Thanks to logging I can even see that several mails were sent. Still, my test SMTP sever (GreenMail) does not receive any emails. How is this even possible? I've intentionally set the transaction isolation to Isolation.SERIALIZABLE so that it should be impossible (as far as I understand transaction isolation) that two scheduled methods access the same Event from the database.
Third problem
To cap it all, when I rerun the failed tests, THEY WORK. But, there are different exceptions on the console (see below). But still, the app starts and the tests finish successfully. There are different test results depending on if I run all tests vs. only the class vs. only the method vs. rerun failed tests. I don't understand how such an indeterministic behaviour can be possible.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: Failed to scan classpath for unlisted entity classes
Caused by: java.nio.channels.ClosedByInterruptException: null
Full stack trace
My code
Test class (UserRegistrationTest)
#ActiveProfiles("test")
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
#SpringBootTest
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
public class UserRegistrationTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper objectMapper;
#Autowired
private Routes routes;
#Autowired
private TestConfig testConfig;
#Resource(name = "validCustomerDTO")
private CustomerDTO validCustomerDTO;
#Resource(name = "validVendorDTO")
private VendorRegistrationDTO validVendorRegistrationDTO;
#Value("${schedule.sendRegistrationConfirmationEmailTaskDelay}")
private Short registrationConfirmationEmailSenderTaskDelay;
private GreenMail smtpServer;
// Setup & tear down
#Before
public void setUp() {
smtpServer = testConfig.getMailServer();
smtpServer.start();
}
#After
public void tearDown() {
smtpServer.stop();
}
// Tests
#Test
public void testCreateCustomerAccount() throws Exception {
mockMvc.perform(
post(routes.getCustomerPath())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(validCustomerDTO)))
.andExpect(status().isCreated());
// When run normally, I get a timeout from the next line
await().atMost(registrationConfirmationEmailSenderTaskDelay + 10000, MILLISECONDS).until(smtpServerReceivedOneEmail());
// Verify correct registration confirmation email was sent
MimeMessage[] receivedMessages = smtpServer.getReceivedMessages();
assertThat(receivedMessages).hasSize(1);
// other checks
// ...
}
#Test
public void testCreateVendorAccount() throws Exception {
mockMvc.perform(
post(routes.getVendorPath())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(validVendorRegistrationDTO)))
.andExpect(status().isCreated());
// When run normally, I get a timeout from the next line
await().atMost(registrationConfirmationEmailSenderTaskDelay + 10000, MILLISECONDS).until(smtpServerReceivedOneEmail());
// Verify correct registration confirmation email was sent
MimeMessage[] receivedMessages = smtpServer.getReceivedMessages();
assertThat(receivedMessages).hasSize(1);
// other checks
// ...
}
// Helper methods
private Callable<Boolean> smtpServerReceivedOneEmail() {
return () -> smtpServer.getReceivedMessages().length == 1;
}
// Test configuration
#TestConfiguration
static class TestConfig {
private static final int PORT = 3025;
private static final String HOST = "localhost";
private static final String PROTOCOL = "smtp";
GreenMail getMailServer() {
return new GreenMail(new ServerSetup(PORT, HOST, PROTOCOL));
}
#Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(HOST);
javaMailSender.setPort(PORT);
javaMailSender.setProtocol(PROTOCOL);
javaMailSender.setDefaultEncoding("UTF-8");
return javaMailSender;
}
}
Task scheduler (BusinessTaskScheduler)
#Component
public class BusinessTaskScheduler {
private final RegistrationTask registrationTask;
#Autowired
public BusinessTaskScheduler(RegistrationTask registrationTask) {
this.registrationTask = registrationTask;
}
#Scheduled(fixedDelayString = "${schedule.sendRegistrationConfirmationEmailTaskDelay}")
public void sendRegistrationConfirmationEmail() {
registrationTask.sendRegistrationConfirmationEmail();
}
}
The code that is called by the scheduled method (RegistrationTask)
#Component
#Transactional(isolation = Isolation.SERIALIZABLE)
public class RegistrationTask {
private final EmailHelper emailHelper;
private final EventService eventService;
private final UserRegistrationService userRegistrationService;
#Autowired
public RegistrationTask(EmailHelper emailHelper, EventService eventService, UserRegistrationService userRegistrationService) {
this.emailHelper = emailHelper;
this.eventService = eventService;
this.userRegistrationService = userRegistrationService;
}
public void sendRegistrationConfirmationEmail() {
Optional<UserAccountCreatedEvent> optionalEvent = eventService.getOldestUncompletedUserAccountCreatedEvent();
if (optionalEvent.isPresent()) {
UserAccountCreatedEvent event = optionalEvent.get();
User user = event.getUser();
RegistrationVerificationToken token = userRegistrationService.createRegistrationVerificationTokenForUser(user);
emailHelper.sendRegistrationConfirmationEmail(token);
eventService.completeEvent(event);
}
}
}
The event service (EventServiceImpl)
#Service
#Transactional(isolation = Isolation.SERIALIZABLE)
public class EventServiceImpl implements EventService {
private final ApplicationEventDAO applicationEventDAO;
private final UserAccountCreatedEventDAO userAccountCreatedEventDAO;
#Autowired
public EventServiceImpl(ApplicationEventDAO applicationEventDAO, UserAccountCreatedEventDAO userAccountCreatedEventDAO) {
this.applicationEventDAO = applicationEventDAO;
this.userAccountCreatedEventDAO = userAccountCreatedEventDAO;
}
#Override
public void completeEvent(ApplicationEvent event) {
if (!event.getStatus().equals(COMPLETED) && Objects.isNull(event.getCompletedAt())) {
event.setStatus(COMPLETED);
event.setCompletedAt(LocalDateTime.now());
applicationEventDAO.save(event);
}
}
#Override
public Optional<UserAccountCreatedEvent> getOldestUncompletedUserAccountCreatedEvent() {
Optional<UserAccountCreatedEvent> optionalEvent = userAccountCreatedEventDAO.findFirstByStatusOrderByCreatedAtAsc(NEW);
if (optionalEvent.isPresent()) {
UserAccountCreatedEvent event = optionalEvent.get();
setEventInProcess(event);
return Optional.of(userAccountCreatedEventDAO.save(event));
}
return Optional.empty();
}
#Override
public void publishEvent(ApplicationEvent event) {
applicationEventDAO.save(event);
}
// Helper methods
private void setEventInProcess(ApplicationEvent event) {
event.setStatus(Status.IN_PROCESS);
event.setInProcessSince(LocalDateTime.now());
}
}
The UserAccountCreatedEvent
application.yml
schedule:
sendRegistrationConfirmationEmailTaskDelay: 5000 # delay between tasks in milliseconds
I am new to scheduling with Spring, so any help is greatly appreciated!

Spring profiles not getting resolved when using it with the spring web based project

in application.properties given : spring.profiles.active=DEV
and in dev config file : mentioned all the mongo connection properties
and added the configuration java file like
#Configuration
#PropertySource("classpath:userIdentity_Dev.properties")
#Profile("DEV")
public class UserIdentityConfigDev
{
}
when running the application the spring profiler is not getting resolved the
below stack trace is received
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userIdentityService': Unsatisfied dependency expressed through field 'userIdentityBusiness'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userIdentityBusiness': Unsatisfied dependency expressed through field 'userIdentityRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userIdentityRepositoryImpl': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'mongodb.userIdentity.host' in string value "${mongodb.userIdentity.host}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
Saying that the ${mongodb.userIdentity.host} property is not resolved
when creating war and jar file for the project the spring profile is not resolved
This is main class:
` #SpringBootApplication(exclude= {DataSourceAutoConfiguration.class ,MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
#PropertySource("classpath:application.properties")
public class ApplicationStart extends SpringBootServletInitializer
{
public static void main(String[] args)
{
SpringApplication.run(ApplicationStart.class,args);
}
}`
below is the property file:
## MongoDB Connection Properties-----------------
MongoDB database
mongodb.userIdentity.database = UserIdentity_CS
isConnectionStringUsed is true then application creates connection as per connectionString else it will use MongoDB single server properties.
mongodb.userIdentity.isConnectionStringUsed = false
connectionString with authentication
mongodb.connectionString = mongodb://sa:Test%40123#SPT-CPU-0259:27017,SPT-CPU-0173:27017/admin?replicaSet=surveillens
connectionString without authentication
mongodb.userIdentity.connectionString = mongodb://localhost:27017/?replicaSet=surveillens
MongoDB single server properties.
mongodb.userIdentity.host = localhost
mongodb.userIdentity.port = 27017
Authentication properties
mongodb.userIdentity.isAuthenticationEnable = false
mongodb.userIdentity.userName = sa
mongodb.userIdentity.password = Test#123
mongodb.userIdentity.authDB = admin
Collection Name for user Identity
mongodb.userIdentity.collectionName = CreditScore
Other properties -----------------------
userIdentity.ValidKeySet = email;phonenumber;_id
userIdentity.logsFolder = ./IdentityLogs/
userIdentity.insertBatchSize = 100
and below is the file .java file where all this properties are used
`
#Configuration
public abstract class MongoDbRepository {
private Class<T> clazz;
private static MongoClient mongoClient = null;
private static MongoDatabase mongoDatabase = null;
private static ObjectMapper mapper = null;
#Value("${mongodb.userIdentity.host}")
private String mongoHost;
#Value("${mongodb.userIdentity.port}")
private int mongoPortNumber;
#Value("${mongodb.userIdentity.database}")
private String mongoDatabaseName;
#Value("${mongodb.userIdentity.userName}")
private String mongoUserName;
#Value("${mongodb.userIdentity.authDB}")
private String mongoAuthDB;
#Value("${mongodb.userIdentity.password}")
private String mongoPassword;
#Value("${mongodb.userIdentity.isAuthenticationEnable}")
private boolean mongoIsAuthEnable;
#Value("${mongodb.userIdentity.isConnectionStringUsed}")
private boolean mongoIsConnectionStringUsed;
#Value("${mongodb.userIdentity.connectionString}")
private String mongoConnectionString;
public final void setClazz(Class<T> clazzToSet)
{
this.clazz = clazzToSet;
}
/**
* Instantiates a new mongo base repository.
* #throws Exception
*/
public MongoDbRepository()
{
//Trigger MongoDB Connection initialization
if(mongoClient == null)
{
prepareMongoConnection();
}
else
{
// Trigger any method to check MongoDB client is connected
mongoClient.getAddress();
}
// Trigger ObjectMapper initialization
if(mapper == null)
prepareObjectMapper();
}
/**
* Instantiates a new mongoDB connection.
* #throws Exception
*/
private void prepareMongoConnection()
{
if (mongoConnectionString != null && !mongoConnectionString.isEmpty())
{
boolean isConnectionStringUsed = mongoIsConnectionStringUsed;
if(isConnectionStringUsed)
{
MongoClientURI clientUri = new MongoClientURI(mongoConnectionString);
mongoClient = new MongoClient(clientUri);
}
else
{
if(mongoIsAuthEnable)
{
MongoCredential credential = MongoCredential.createCredential(mongoUserName, mongoAuthDB, mongoPassword.toCharArray());
mongoClient = new MongoClient( new ServerAddress(mongoHost, mongoPortNumber), Arrays.asList(credential));
}
else
mongoClient = new MongoClient(mongoHost, mongoPortNumber);
}
// Trigger any method to check MongoDB client is connected
mongoClient.getAddress();
// Get Database from mongoClient.
mongoDatabase = mongoClient.getDatabase(mongoDatabaseName);
}
}
/**
* Get an objectMapper.
*/
private void prepareObjectMapper()
{
mapper = CommonFunctions.getObjectMapper();
}
/**
* Get the MongoDB collection object from MongoDB.
*
* #param collectionName is Name of a MongoDB collection
* #return Collection object
* #throws Exception
*/
private MongoCollection<Document> getCollection(String collectionName) throws Exception
{
if(mongoClient == null)
prepareMongoConnection();
return mongoDatabase.getCollection(collectionName);
}
/* ------- Find functions ------- */
/**
* Find one documents from mongoDB collection.
*
* #param collectionName the collection name
* #param query the query document - set to empty document means no query filtering.
*
* #return entityObj the entity Object
* #throws Exception the exception
*/
public T findOne(String collectionName, Object query) throws Exception
{
if(clazz == null)
throw new NullPointerException("ST224 - Generic class is null - set the generic class before perform MongoDB operation");
MongoCollection<Document> collection = getCollection(collectionName);
Document mongoDoc = collection.find(convertToBsonDocument(query)).first();
String jsonStr = mapper.writeValueAsString(mongoDoc);
T entityObj = mapper.readValue(jsonStr, clazz);
return entityObj;
}
}`

Unable to setup MiniProfiler w/ Enity Framework 4.0 (Not code first)

I installed MiniProfiler and MiniProfiler.EF in my project via nuget.
Before using MiniProfiler I would open a connection using this in my model repository:
public class NotificationRepository
{
private CBNotificationModel.CB_NotificationEntities db;
public NotificationRepository()
{
db = new CB_NotificationEntities();
}
public NotificationContact GetNotificationContacts()
{
return db.NotificationContacts.ToList();
}
}
To use mini profiler I created:
public static class ConnectionHelper
{
public static CB_NotificationEntities GetEntityConnection()
{
var conn = new StackExchange.Profiling.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
return ObjectContextUtils.CreateObjectContext<CB_NotificationEntities>(conn); // resides in the MiniProfiler.EF nuget pack
}
public static EntityConnection GetConnection()
{
return new EntityConnection(ConfigurationManager.ConnectionStrings["CB_NotificationEntities"].ConnectionString);
}
}
The model repository now uses
db = ConnectionHelper.GetEntityConnection();
However this gives the error:
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Am I missing a step? I tried adding MiniProfilerEF.Initialize() and MiniProfilerEF.Initialize_EF42() in Application_start() however that just changes the errors given.
There does not seem to be much information for setting up a entity framework project to use miniprofiler unless it is codefirst.
I was able to get this working by changing my ConnectionHelper class to the following:
public static class ConnectionHelper
{
public static CB_NotificationEntities GetEntityConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["CB_NotificationEntities"].ConnectionString;
var ecsb = new EntityConnectionStringBuilder(connectionString);
var sqlConn = new SqlConnection(ecsb.ProviderConnectionString);
var pConn = new StackExchange.Profiling.Data.EFProfiledDbConnection(sqlConn, MiniProfiler.Current);
var context = ObjectContextUtils.CreateObjectContext<CB_NotificationEntities>(pConn);
return context;
}
}

Resources