I try to save the object into sessionmap but it is giving me an exception
public class testclass {
public static void main(String[] args) throws IOException
{
UserInfo ui = new UserInfo();
UserLogin ul= new UserLogin();
ui.setAdds("India");
ui.setEId("someone#yahoo.com");
ui.setFName("someone");
ui.setLName("someone2");
ui.setStatus("single");
ul.setPswd("somename");
ul.setUserId("121");
ul.setUserinfo(ui);
AnnotationConfiguration config = new AnnotationConfiguration();
config.configure("hibernate.cfg.xml");
//new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();
System.out.println("Session configured");
session.beginTransaction();
session.save(ul);
System.out.println("object saved");
Query q = session.createQuery("from UserLogin where UserId='121'");
UserLogin user = (UserLogin)q.uniqueResult();
if(user!=null)
{
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("User",user);
UserLogin hd = (UserLogin)sessionMap.get("User");
System.out.println("the user id is "+hd.getUserId());
}
session.getTransaction().commit();
}
Exception:
Exception in thread "main" java.lang.NullPointerException at BeanMngr.testclass.main(testclass.java:58) Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)
How is this problem caused and how can I solve it?
If you want to store an object in jsf session do the following:
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("yourKey", yourObject);
The SessionMap is a Map<String, Object> and you can access your stored objects with the help of the get(Object key) method.
Related
I want to register and execute stored proc. I am using spring+Java with cosmos DB. Everytime I stop my application and restart it , it tried to create new sproc and since it already exists in cosmos DB it fails with below error . Is their any option available like "only create if not exist". I am fetching js file from src/main/resources folder.
I am following below doc to register the stored proc
https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-use-stored-procedures-triggers-udfs?tabs=java-sdk
#Configuration
public class StoredProcConfig
{
#Autowired
#Qualifier(BeansConstants.PAYMENT_CONTAINER)
CosmosContainer container;
#Bean
public CosmosStoredProcedureResponse registerSp() throws IOException
{
InputStream is = getFileFromResourceAsStream("storedProcedures/createStudent.js");
CosmosStoredProcedureProperties definition = new CosmosStoredProcedureProperties("spCreateToDoItems",
IOUtils.toString(is, StandardCharsets.UTF_8));
return container.getScripts().createStoredProcedure(definition);
}
private InputStream getFileFromResourceAsStream(String fileName)
{
// The class loader that loaded the class
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);
// the stream holding the file content
if (inputStream == null)
{
throw new IllegalArgumentException("file not found! " + fileName);
} else
{
return inputStream;
}
}
}
Error
Caused by: com.azure.cosmos.CosmosException: {"innerErrorMessage":"Message: {\"Errors\":[\"Resource with specified id, name, or unique index already exists.\"]}
Modify your registerSp() bean as below:
private static final Logger logger = LoggerFactory.getLogger(CosmosConfiguration.class);
#Bean
public CosmosStoredProcedureResponse registerSp() throws IOException
{
InputStream is = getFileFromResourceAsStream("storedProcedures/createStudent.js");
CosmosStoredProcedureProperties definition = new CosmosStoredProcedureProperties("spCreateToDoItems",
IOUtils.toString(is, StandardCharsets.UTF_8));
return createStoredProcedureIfNotExists(definition);
}
public CosmosStoredProcedureResponse createStoredProcedureIfNotExists(CosmosStoredProcedureProperties definition){
try {
CosmosStoredProcedureResponse storedProc = container.getScripts().getStoredProcedure(definition.getId()).read();
logger.info("found stored proc");
return storedProc;
}
catch (CosmosException e){
logger.info("stored proc not found, creating....");
return container.getScripts().createStoredProcedure(definition);
}
}
I'm using spring boot 2.4.1 and spring security SAML2 support
I successfully configured my Service Provider. I created a self-signed certificate and I'm trying to use an IDP that requires signed AuthnRequests.
This is my RelyingPartyRegistrationRepository configuration:
#Bean
public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception{
KeyStore ks = KeyStore.getInstance(this.keyStoreType);
char[] pwd = keyStorePassword != null ? keyStorePassword.toCharArray() : null;
String ksName = keyStoreName.replaceAll("classpath:", "");
Resource keystoreRes = new ClassPathResource(ksName);
ks.load(keystoreRes.getInputStream(), pwd);
PrivateKey privateKey = (PrivateKey)ks.getKey(keyStoreAlias, keyStoreKeyPassword.toCharArray());
X509Certificate cert = (X509Certificate) ks.getCertificate(keyStoreAlias);
RelyingPartyRegistration registration = RelyingPartyRegistrations
.fromMetadataLocation(assertingPartyMetadataLocation)
.registrationId(registrationId)
.entityId(spEntityId)
.signingX509Credentials((c) -> c.add(Saml2X509Credential.signing(privateKey, cert)))
.decryptionX509Credentials((c)->c.add(Saml2X509Credential.decryption(privateKey, cert)))
.build();
return new InMemoryRelyingPartyRegistrationRepository(registration);
}
The application successfully starts but,, every time I makes a new request, I got an exception on the IDP side because no KeyInfo element is found in the AuthnRequest
By seeing my application logs, I found this log:
2021-01-06 12:20:35,650 23472 [XNIO-1 task-7] INFO o.o.x.s.support.SignatureSupport - No KeyInfoGenerator was supplied in parameters or resolveable for credential type org.opensaml.security.x509.X509Credential, No KeyInfo will be generated for Signature
I can't understand if I'm missing something in the configuration.
Please note that the same happens also with a certificate released by a trusted CA and not only with self-signed certificate. So I'm thinking it's a kind of configuration mistake I'm doing or a kind of bug.
May you kindly give me tip in how to solve this issue?
Angelo
UPDATE
I solved my current issue. Anyway I think it's a my mistake. Basically I modified the org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationRequestFactory
I added the following method:
private KeyInfoGenerator x509KeyInfoGenerator() {
X509KeyInfoGeneratorFactory generator = new X509KeyInfoGeneratorFactory();
generator.setEmitEntityCertificate(true);
generator.setEmitEntityCertificateChain(true);
return generator.newInstance();
}
I called this method here:
private SignatureSigningParameters resolveSigningParameters(RelyingPartyRegistration relyingPartyRegistration) {
List<Credential> credentials = resolveSigningCredentials(relyingPartyRegistration);
List<String> algorithms = Collections.singletonList(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256);
String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS;
SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver();
CriteriaSet criteria = new CriteriaSet();
BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration();
signingConfiguration.setSigningCredentials(credentials);
signingConfiguration.setSignatureAlgorithms(algorithms);
signingConfiguration.setSignatureReferenceDigestMethods(digests);
signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization);
criteria.add(new SignatureSigningConfigurationCriterion(signingConfiguration));
try {
SignatureSigningParameters parameters = resolver.resolveSingle(criteria);
parameters.setKeyInfoGenerator(x509KeyInfoGenerator());
Assert.notNull(parameters, "Failed to resolve any signing credential");
return parameters;
}
catch (Exception ex) {
throw new Saml2Exception(ex);
}
}
Now I don't have errors on IdP side but I'm thinking I'm missing something in my configuration. This is my whole web security configuration:
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class ApplicazioneMockWebSecurityCfg extends WebSecurityConfigurerAdapter {
static {
OpenSamlInitializationService.requireInitialize((registry) -> {
X509KeyInfoGeneratorFactory generator = new X509KeyInfoGeneratorFactory();
generator.setEmitEntityCertificate(true);
generator.setEmitEntityCertificateChain(true);
NamedKeyInfoGeneratorManager manager = new NamedKeyInfoGeneratorManager();
manager.registerDefaultFactory(generator);
});
}
#Value("${applicazione.mock.external.idp.metadata.location}")
private String assertingPartyMetadataLocation;
#Value("${applicazione.mock.external.idp.metadata.registration.id}")
private String registrationId;
#Value("${server.ssl.key-alias}")
private String keyStoreAlias;
#Value("${server.ssl.key-password}")
private String keyStoreKeyPassword;
#Value("${server.ssl.key-store-password}")
private String keyStorePassword;
#Value("${server.ssl.keystore}")
private String keyStoreName;
#Value("${server.ssl.key-store-type}")
private String keyStoreType;
#Value("${sael.spid.service.provider.applicazione.mock.metadata.entity.id}")
private String spEntityId;
public static final String LOGOUT_URL = "/public/logout";
public static final String LOGIN_PAGE = "/public/home";
#Override
protected void configure(HttpSecurity http) throws Exception {
OpenSamlAuthenticationProvider authenticationProvider = new OpenSamlAuthenticationProvider();
authenticationProvider.setResponseAuthenticationConverter(responseToken -> {
// Saml2Authentication authentication = OpenSamlAuthenticationProvider
// .createDefaultResponseAuthenticationConverter()
// .convert(responseToken);
Assertion assertion = responseToken.getResponse().getAssertions().get(0);
String username = assertion.getSubject().getNameID().getValue();
List<AttributeStatement> attrStatements = assertion.getAttributeStatements();
String valoreAttributo = null;
Map<String, String> samlAttributes = new HashMap<>();
for (AttributeStatement attrStatement : attrStatements) {
List<Attribute> attrs = attrStatement.getAttributes();
for (Attribute attr : attrs) {
String nomeAttributo = attr.getName();
List<XMLObject> valoriAttributo = attr.getAttributeValues();
//In genere la lista dei valori รจ di 1 elemento
XMLObject valueObj = valoriAttributo.get(0);
valoreAttributo = getValue(valueObj, valoreAttributo);
samlAttributes.put(nomeAttributo, valoreAttributo);
}
}
if( !StringUtils.hasText(valoreAttributo) ) {
throw new IllegalStateException("Impossibile proseguire. Codice Fiscale non trovato tra gli attributi SAML");
}
UserDetails userDetails = new ApplicazioneMockLoggedUser(username, "[PROTECTED]", samlAttributes, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
return new SaelSamlAuthentication(userDetails);
});
Converter<HttpServletRequest, RelyingPartyRegistration> relyingPartyRegistrationResolver =
new DefaultRelyingPartyRegistrationResolver(this.relyingPartyRegistrations());
http
.authorizeRequests()
.antMatchers("/protected/**")
.authenticated()
.antMatchers("/public/**")
.permitAll()
.and()
.saml2Login(authorize ->{
authorize
.loginPage(LOGIN_PAGE)
.authenticationManager(new ProviderManager(authenticationProvider))
;
})
.logout(logout->{
logout
.logoutUrl(LOGOUT_URL)
.logoutSuccessHandler(saelLogoutSuccessHanlder())
.logoutRequestMatcher(saelRequestMatcher())
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
//.logoutSuccessUrl(LOGIN_PAGE+"?logout")
.permitAll();
})
.addFilterBefore(new Saml2MetadataFilter(relyingPartyRegistrationResolver, new OpenSamlMetadataResolver()), Saml2WebSsoAuthenticationFilter.class);
}
#Bean
public RequestMatcher saelRequestMatcher() {
return new SaelRequestMatcher();
}
#Bean
public LogoutSuccessHandler saelLogoutSuccessHanlder() {
return new SaelLogoutSuccessHandler();
}
#Bean
Saml2AuthenticationRequestFactory authenticationRequestFactory(
AuthnRequestConverter authnRequestConverter) {
OpenSamlAuthenticationRequestFactory authenticationRequestFactory =
new OpenSamlAuthenticationRequestFactory();
authenticationRequestFactory.setAuthenticationRequestContextConverter(authnRequestConverter);
return authenticationRequestFactory;
}
#Bean
public RelyingPartyRegistrationRepository relyingPartyRegistrations() throws Exception{
KeyStore ks = KeyStore.getInstance(this.keyStoreType);
char[] pwd = keyStorePassword != null ? keyStorePassword.toCharArray() : null;
String ksName = keyStoreName.replaceAll("classpath:", "");
Resource keystoreRes = new ClassPathResource(ksName);
ks.load(keystoreRes.getInputStream(), pwd);
PrivateKey privateKey = (PrivateKey)ks.getKey(keyStoreAlias, keyStoreKeyPassword.toCharArray());
X509Certificate cert = (X509Certificate) ks.getCertificate(keyStoreAlias);
RelyingPartyRegistration registration = RelyingPartyRegistrations
.fromMetadataLocation(assertingPartyMetadataLocation)
.registrationId(registrationId)
.entityId(spEntityId)
.signingX509Credentials((c) -> c.add(Saml2X509Credential.signing(privateKey, cert)))
.decryptionX509Credentials((c)->c.add(Saml2X509Credential.decryption(privateKey, cert)))
.build();
return new InMemoryRelyingPartyRegistrationRepository(registration);
}
private String getValue( XMLObject valueObj, String defaultValue ) {
if( valueObj instanceof XSStringImpl ) {
XSStringImpl stringImpl = (XSStringImpl)valueObj;
return stringImpl.getValue();
}
return defaultValue;
}
}
May you help me in understanding if I'm missing something (I think I'm missing something)
We are securing out REST services using spring security OAuth2. Applications can call into either the /oauth/authorize, /oauth/token or /rest-api endpoints. The token and rest-api endpoints are stateless and do not need a session.
Can we invalidate the session after the user is authenticated? If so, what is the best approach. We want the user to sign-in always whenever a call to /oauth/authorize is made. Currently, calls to /oauth/authorize are skipping authentication whenever a session exists.
Understanding that the question is a bit old, I hope that the following could be helpful for those who search for the correct answer for the question
OP asked not about tokens invalidation, but how to invalidate httpSession on Spring OAuth2 server right after user authentication successfully passed and a valid access_token or authorization_code (for subsequent getting of access_token) returned to a client.
There is no out-of-the-box solution for this use-case still. But working workaround from the most active contributor of spring-security-oauth, Dave Syer, could be found here on GitHub
Just copy of the code from there:
#Service
#Aspect
public class SessionInvalidationOauth2GrantAspect {
private static final String FORWARD_OAUTH_CONFIRM_ACCESS = "forward:/oauth/confirm_access";
private static final Logger logger = Logger.getLogger(SessionInvalidationOauth2GrantAspect.class);
#AfterReturning(value = "within(org.springframework.security.oauth2.provider.endpoint..*) && #annotation(org.springframework.web.bind.annotation.RequestMapping)", returning = "result")
public void authorizationAdvice(JoinPoint joinpoint, ModelAndView result) throws Throwable {
// If we're not going to the confirm_access page, it means approval has been skipped due to existing access
// token or something else and they'll be being sent back to app. Time to end session.
if (!FORWARD_OAUTH_CONFIRM_ACCESS.equals(result.getViewName())) {
invalidateSession();
}
}
#AfterReturning(value = "within(org.springframework.security.oauth2.provider.endpoint..*) && #annotation(org.springframework.web.bind.annotation.RequestMapping)", returning = "result")
public void authorizationAdvice(JoinPoint joinpoint, View result) throws Throwable {
// Anything returning a view and not a ModelView is going to be redirecting outside of the app (I think).
// This happens after the authorize approve / deny page with the POST to /oauth/authorize. This is the time
// to kill the session since they'll be being sent back to the requesting app.
invalidateSession();
}
#AfterThrowing(value = "within(org.springframework.security.oauth2.provider.endpoint..*) && #annotation(org.springframework.web.bind.annotation.RequestMapping)", throwing = "error")
public void authorizationErrorAdvice(JoinPoint joinpoint) throws Throwable {
invalidateSession();
}
private void invalidateSession() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
HttpSession session = request.getSession(false);
if (session != null) {
logger.warn(String.format("As part of OAuth application grant processing, invalidating session for request %s", request.getRequestURI()));
session.invalidate();
SecurityContextHolder.clearContext();
}
}
}
add pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
Another solution could be to set session time out to some very small value. The simplest way to achieve that is put the following to application.yml config:
server:
session:
timeout: 1
But it's not ideal solution as the minimum value could be provider is 1 (zero is reserved for infinite sessions) and it is in minutes not in seconds
From what I understand, you are trying to programmatically logout after you have undertaken certain set of actions. Probably you should look into the SecurityContextLogoutHandler and see how it works. There is a method for logout there. I think calling it as an advice will solve your problem.
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
Assert.notNull(request, "HttpServletRequest required");
if (invalidateHttpSession) {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
SecurityContextHolder.clearContext();
}
First: in your configuration declare bean with token store for oauth
#Bean
#Primary
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
For controller approach we made the following class
#Controller
public class TokenController {
#RequestMapping(value = "/oauth/token/revoke", method = RequestMethod.POST)
public #ResponseBody void create(#RequestParam("token") String value) {
this.revokeToken(value);
}
#Autowired
TokenStore tokenStore;
public boolean revokeToken(String tokenValue) {
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
if (accessToken == null) {
return false;
}
if (accessToken.getRefreshToken() != null) {
tokenStore.removeRefreshToken(accessToken.getRefreshToken());
}
tokenStore.removeAccessToken(accessToken);
return true;
}
}
If you don't wan't to use this approach you can grab current user's token autowiring Principal:
OAuth2Authentication authorization = (OAuth2Authentication) principal;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authorization.getDetails();
String token = details.getTokenValue();
Or even autowiring OAuth2Authentication:
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
String token = details.getTokenValue();
I can offer such an option (according to #de_xtr recomendation):
import static org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes;
#Slf4j
#Component
#Aspect
public class InvalidateSessionAspect {
private final LogoutHandler logoutHandler;
public InvalidateSessionAspect() {
logoutHandler = new SecurityContextLogoutHandler();
}
#Pointcut("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
public void postAccessTokenPointcut() {
}
#AfterReturning(value = "postAccessTokenPointcut()", returning = "entity")
public void invalidateSession(JoinPoint jp, Object entity) {
log.debug("[d] Trying to invalidate the session...");
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) currentRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
logoutHandler.logout(request, null, null);
log.debug("[d] Session has been invalidated");
}
}
And the option without any aspects:
#Slf4j
class LogoutHandlerInterceptor implements HandlerInterceptor {
#Override
public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object h, ModelAndView view) {
HttpSession session = req.getSession(false);
if (session != null) {
log.debug("[d] Trying to invalidate the session...");
session.invalidate();
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(null);
SecurityContextHolder.clearContext();
log.debug("[d] Session has been invalidated");
}
}
}
#Configuration
#EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
//...
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.addInterceptor(new LogoutHandlerInterceptor())
// ...
;
}
}
I'm following the tutorial found here to create a JWT token to access the REST API of JIRA. I do not have any problem accessing endpoints without passing query strings like /rest/api/2/project and /rest/api/2/issue/ISSUE-KEY but I get 401 Unauthorized when trying to pass query strings, say /rest/api/2/user/assignable/search?project=PROJECT-KEY
I'm guessing I'm missing out something, specificially the generation of canonical URL,
Here is the code that generates the get request and JWT token:
#Override
public CloseableHttpResponse get(String url) throws HttpException,
IOException, NoSuchAlgorithmException, ParseException,
JOSEException {
CloseableHttpClient client = HttpClientBuilder.create()
.setUserAgent("Kevin 6.9").build();
String token = createToken(url, JIRAClient.Method.GET);
HttpGet method = new HttpGet(jwt.getBaseUrl() + url);
method.setHeader("Authorization", "JWT " + token);
return client.execute(method);
}
/**
* Create JWT token
*
* #return
* #throws UnsupportedEncodingException
* #throws NoSuchAlgorithmException
*/
private String createToken(String apiPath, JIRAClient.Method method)
throws UnsupportedEncodingException, NoSuchAlgorithmException {
long issuedAt = System.currentTimeMillis() / 1000L;
long expiresAt = issuedAt + 1000L;
String httpMethod = method.toString();
System.out.println(httpMethod);
String contextPath = "/jira";
JwtJsonBuilder jwtBuilder = new JsonSmartJwtJsonBuilder()
.issuedAt(issuedAt).expirationTime(expiresAt)
.issuer(jwt.getKey());
HashMap<String, String[]> parameters = new HashMap<String, String[]>();
CanonicalHttpUriRequest canonical = new CanonicalHttpUriRequest(
httpMethod, apiPath, contextPath, parameters);
System.out.println("Canonical : " + canonical.getRelativePath());
JwtClaimsBuilder.appendHttpRequestClaims(jwtBuilder, canonical);
JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory();
String jwtbuilt = jwtBuilder.build();
String jwtToken = jwtWriterFactory.macSigningWriter(
SigningAlgorithm.HS256, jwt.getSharedSecret()).jsonToJwt(
jwtbuilt);
return jwtToken;
}
Note that I am passing an empty HashMap<String, String[]> to the CanonicalHttpUriRequest... is this correct?
Apparently the Map<String, String[]> is required to generate the appropriate canonical URI.
Note that I am passing an empty HashMap<String, String[]> to the
CanonicalHttpUriRequest... is this correct?
I modified my method signature so I can pass it as a parameter. Note: createQueryString is a method inside my class that manually creates the query String from the parameter map.
#Override
public CloseableHttpResponse get(String url,
#SuppressWarnings("rawtypes") Map parameters) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create()
.setUserAgent("Kevin 5.0").build();
String token = createToken(url, JIRAClient.Method.GET, parameters);
HttpGet method = new HttpGet(jwt.getBaseUrl() + url
+ createQueryString(parameters));
method.setHeader("Authorization", "JWT " + token);
return client.execute(method);
}
And it works.
#Test
public void testJQL() throws Exception {
HashMap param = new HashMap();
param.put("jql", new String[] {"project=COR"});
param.put("startAt", new String[] {"0"});
HttpResponse response = client.get("/rest/api/2/search", param);
Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
}
I am busy with an e-commerce web application using visual studio 2005 and IIS 7
I got this error
System.TypeInitializationException was unhandled by user code
Message="The type initializer for 'ShopConfiguration' threw an exception."
Source="App_Code.r-ihwy-d"
TypeName="ShopConfiguration"
StackTrace:
at ShopConfiguration.get_DbProviderName()
at GenericDataAccess.CreateCommand() in c:\inetpub\wwwroot\Beadafrican\App_Code\GenericDataAccess.cs:line 63
at CatalogAccess.GetDepartments() in c:\inetpub\wwwroot\Beadafrican\App_Code\CatalogAccess.cs:line 28
at UserControls_DepartmentsList.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\Beadafrican\UserControls\DepartmentsList.ascx.cs:line 22
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
If I look at the code it refers to I dont see what is wrong? Here is the code if anyone can please assist it would be great!
GenericDataAccess.cs:
public static class GenericDataAccess
{
//static constructor
static GenericDataAccess()
{
//
// TODO: Add constructor logic here
//
}
//execute a command and returns the result as a DataTable Object
public static DataTable ExecuteSelectCommand(DbCommand command)
{
//The DataTable to be returned
DataTable table;
//Execute the command making sure the connection gets closed in the end
try
{
//open the data connection
command.Connection.Open();
//Execute the command and save the results in a DataTable
DbDataReader reader = command.ExecuteReader();
table = new DataTable();
table.Load(reader);
//Close the reader
reader.Close();
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw ex;
}
finally
{
//Close the connection
command.Connection.Close();
}
return table;
}
//creates and prepares a new DbCommand object on a new connection
public static DbCommand CreateCommand()
{
//Obtain the database provider name
string dataProviderName = ShopConfiguration.DbProviderName;
//Obtain the database connection string
string connectionString = ShopConfiguration.DbConnectionString;
//Create a new data provider factory
DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
//Obtain a database specific connection object
DbConnection conn = factory.CreateConnection();
//Set the connection string
conn.ConnectionString = connectionString;
//Create a database specific command object
DbCommand comm = conn.CreateCommand();
//Set the command type to stored procedure
comm.CommandType = CommandType.StoredProcedure;
//Return the initialised command object
return comm;
}
CatalogAccess.cs
public static class CatalogAccess
{
static CatalogAccess()
{
//
// TODO: Add constructor logic here
//
}
//Retrieve the list of departments
public static DataTable GetDepartments()
{
//get configured DbCommand object
DbCommand comm = GenericDataAccess.CreateCommand();
//set the stored procedure name
comm.CommandText = "GetDepartments";
//execute the stored procedure and return the results
return GenericDataAccess.ExecuteSelectCommand(comm);
}
}
DepartementList.ascx.cs
public partial class UserControls_DepartmentsList : System.Web.UI.UserControl
{
// Load department details into the DataList
protected void Page_Load(object sender, EventArgs e)
{
// don't reload data during postbacks
{
// CatalogAccess.GetDepartments returns a DataTable object containing
// department data, which is read in the ItemTemplate of the DataList
list.DataSource = CatalogAccess.GetDepartments();
// Needed to bind the data bound controls to the data source
list.DataBind();
}
}
}
the ShopConfiguration class
{
//Caches the connection string
private readonly static string dbConnectionString;
//Caches the data provider name
private readonly
static string dbProviderName;
//stores the number of products per page
private readonly static int productsPerPage;
//Stores the product description length for product lits
private readonly static int productDescriptionLenght;
//Store the name of your shop
private readonly static string siteName;
//Initialize various proeprties in the constructor
static ShopConfiguration()
{
dbConnectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
dbProviderName = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ProviderName;
productsPerPage = Int32.Parse(ConfigurationManager.AppSettings["ProductsPerPage"]);
productDescriptionLenght = Int32.Parse(ConfigurationManager.AppSettings["ProductDescriptionLenght"]);
siteName = ConfigurationManager.AppSettings["SiteName"];
}
//Returns the connection string for BeadAfrican database
public static string DbConnectionString
{
get
{
return dbConnectionString;
}
}
//Returns the data provider name
public static string DbProviderName
{
get
{
return dbProviderName;
}
}
I am quite sure that the TypeInitializationException that is thrown has another exception assigned to its InnerException property. If you examine that exception, I think you will find the real cause of your problem.
Sounds like you have specified an invalid setting for DbProviderName so internal checking code reports this exception. You'd better review the connection string settings.