Error when using Code First in web service "System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string." - web-services

I'm using Code First. Everything works just fine (inserts, updates, selects) everything is tested. The problem comes when I try to use the web services. I get the error "System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.". Looking at the inner exception I get this message "Could not determine storage version; a valid storage connection or a version hint is required.".
The web service Code:
/// <summary>
/// Summary description for UserServices
/// </summary>
[WebService(Namespace = "http://localhost:3955/WebServices/UserServices")]
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UserServices : System.Web.Services.WebService
{
[WebMethod]
public bool LoginControlPanelUser(string user, string password)
{
if(Membership.ValidateUser(user, password))
{
return DbUsersDAO.HasAuthenticationType(user, password);
}
return false;
}
}
The DAO code:
public static bool HasAuthenticationType(string user, string authenticationTypeCode)
{
try
{
using (VirtusCloudCoreContext ctx = new VirtusCloudCoreContext())
{
DBUser User = ctx.DBUsers.SingleOrDefault(u => u.Login.Equals(user) && u.Active.Equals(true));
if (User != null)
{
return DBAuthenticationTypesDAO.GetById(User.DBAuthenticationTypeId).Name.Equals("Admin");
}
}
return false;
}
catch (Exception ex)
{
ErrorsHelper.InsertError(ex);
throw ex;
}
}
The Context class:
public VirtusCloudCoreContext()
{
Database.SetInitializer<VirtusCloudCoreContext>(new VirtusCloudCoreContextInitializer());
this.Database.Connection.ConnectionString = "Data Source=localhost\SQLEXPRESS;Database=DatabaseName;User Id=******;Password=*******;" ;
}
I get the exception when I try to get the user.... Any ideas?

This error occurs often when the connection string is wrong but I think in your case it's because you're trying to manually set the connection string.
Try making your context inherit from DbContext and take a connection string in your constructor which it passes through to the base constructor, like this:
public class VirtualCloudCoreContext : DbContext {
public VirtualCloudCoreContext(string connectionString)
: base (connectionString) {
}
}

I'm using a new DB-generated EDMX in VS2012 Web Project with a separate class file - both projects have EF 6.1.1 installed. Even though I'm using SQL 2012, I had to edit the EDMX file directly and change it to ProviderManifestToken="2008" from 2012.
Not sure if related to Telerik Grid/EntityDataSource or not. More mention of this issue here but related to VS2013.

Related

doNothing method does not work with void static method

I am assigned to add unit test code coverage to a 15 years old legacy project which is not using IoC and 0 unit test. I am not allowed to refactor the code since it works perfect fine on production, management does not want other teams get involved for refactoring such as QA testing, etc.
Service class has a performService method has following code
public void performService(requestMessage, responseMessage) {
UserAccount userAccount = requestMessage.getUserAccount();
GroupAccount groupAccount = requestMessage.getGroupAccount();
Type type = requestMessage.getType();
StaticServiceCall.enroll(userAccount, groupAccount, type);
response.setStatus(Status.SUCCESS);
}
This StaticServiceCall.enroll method is calling remote service. My unit test is
#RunWith(PowerMockRunner.class)
#PrepareForTest(StaticServiceCall.class)
public class EnrollmentServiceTest {
#Test
public void testPerformService() {
mockStatic(StaticServiceCall.class);
doNothing().when(StaticServiceCall.enroll(any(UserAccount.class), any(GroupAccount.class), any(Type.class)));
service.performService(requestMessage, responseMessage);
assertEquals("Enrollment should be success, but not", Status.SUCCESS, response.getStatus);
}
Eclipse complains with The method when(T) in the type Stubber is not applicable for the arguments (void)
Eclipse stops complain if test code change to
mockStatic(StaticServiceCall.class);
doNothing().when(StaticServiceCall.class);
StaticServiceCall.enroll(any(UserAccount.class), any(GroupAccount.class), any(Type.class));
service.performService(requestMessage, responseMessage);
assertEquals("Enrollment should be success, but not", Status.SUCCESS, response.getStatus);
Test case failed with UnfinishedStubbingException. I am using powermock 1.6.6
There is a misconception on your end. You think that you need to say that doNothing() should do nothing.
That is not necessary! As these lines
#PrepareForTest(StaticServiceCall.class) ... and
mockStatic(StaticServiceCall.class);
are sufficient already.
You want to prevent the "real" content of that static method to run when the method is invoked during your test. And that is what mockStatic() is doing.
In other words: as soon as you use mockStatic() the complete implementation of the real class is wiped. You only need to use when/then/doReturn/doThrow in case you want to happen something else than nothing.
Meaning: just remove that whole doNothing() line!
#GhostCat - Thank you for your answer, it solved problem, my misconception is coming from this test case
#Test
public void testEnrollmentServiceSuccess() {
RequestMessage requestMessage = new RequestMessage();
requestMessage.setName("ENROLL");
ResponseMessage responseMessage = new ResponseMessage();
EnrollmentService mockService = mock(EnrollmentService.class);
mockService.performService(any(RequestMessage.class), any(ResponseMessage.class));
mockStatic(ClientManager.class);
when(ClientManager.isAuthenticated()).thenReturn(true);
ServiceImpl service = new ServiceImpl();
service.performService(requestMessage, responseMessage);
verify(mockService).performService(any(RequestMessage.class), any(ResponseMessage.class));
}
Here is the code snippet of ServiceImpl class based name of the request message calling different service class
public void performService(RequestMessage request, ResponseMessage response) {
try {
if (request == null) {
throw new InvalidRequestFormatException("null message");
}
if (!ClientManager.isAuthenticated()) {
throw new ServiceFailureException("not authenticated");
}
// main switch for known services
if ("ENROLL".equals(request.getName())) {
service = new EnrollmentService();
service.performService(request, response);
} else if ("VALIDATE".equals(request.getName())) {
...
Although the test passed,real implementation in EnrollmentService got called and exceptions thrown due to barebone RequestMessage object, then I googled out doNothing, thanks again for your clarification

#WithUserDetails does not seem to work

I have an application in which I use Spring Social Security for authentication and authorization. Unfortunately I am having some problems with mocking Spring Security. It seems that it does not work at all.
I have a REST controller that returns 404 Not Found if the identifier of the entity it should return is not available. If the user is not logged in then any page redirects to the social login page of my app.
I have read here that the #WithUserDetails annotation would suit me the best.
So my test method looks like this
#Test
#SqlGroup({
#Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, statements = "INSERT INTO UserAccount(id, creationtime, modificationtime, version, email, firstname, lastname, role, signinprovider) VALUES (1, '2008-08-08 20:08:08', '2008-08-08 20:08:08', 1, 'user', 'John', 'Doe', 'ROLE_USER', 'FACEBOOK')"), })
#Rollback
#WithUserDetails
public void ifNoTeamsInTheDatabaseThenTheRestControllerShouldReturnNotFoundHttpStatus() {
ResponseEntity<String> response = restTemplate.getForEntity("/getTeamHistory/{team}", String.class, "Team");
Assert.assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
}
But this does not seem to work at all. It looks like the test method is executed with anonymous user, because the status I get is 200 OK.
My test class is annotated like this
#RunWith(SpringRunner.class)
#ActiveProfiles("dev")
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
#Transactional
public class TeamRestControllerTest {
//...
}
Has anyone ever experienced such an issue with mocking Spring Security that is delivered by Spring Social?
I'm unable to test it at the moment, but here's a possible solution.
Looking at #WithUserDetails implementation:
#WithSecurityContext(factory = WithUserDetailsSecurityContextFactory.class)
public #interface WithUserDetails {
...
}
final class WithUserDetailsSecurityContextFactory implements
WithSecurityContextFactory<WithUserDetails> {
private BeanFactory beans;
#Autowired
public WithUserDetailsSecurityContextFactory(BeanFactory beans) {
this.beans = beans;
}
public SecurityContext createSecurityContext(WithUserDetails withUser) {
String beanName = withUser.userDetailsServiceBeanName();
UserDetailsService userDetailsService = StringUtils.hasLength(beanName)
? this.beans.getBean(beanName, UserDetailsService.class)
: this.beans.getBean(UserDetailsService.class);
String username = withUser.value();
Assert.hasLength(username, "value() must be non empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), principal.getAuthorities());
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
}
You could create the Security Context of your choice following the same pattern:
#Target({ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Inherited
#Documented
#WithSecurityContext(factory = WithoutUserFactory.class)
public #interface WithoutUser {
}
public class WithoutUserFactory implements WithSecurityContextFactory<WithoutUser> {
public SecurityContext createSecurityContext(WithoutUser withoutUser) {
return SecurityContextHolder.createEmptyContext();
}
}
The other available annotations: WithAnonymousUser, WithMockUser, WithSecurityContext (and WithUserDetails)
Adding my workaround, probably it can be helpful for someone else.
I think I met the same problem:
A #Testcontainers (for PostgreSQL DB emulation) + #SpringBootTest test.
Mocked the SecurityContext via annotation with #WithSecurityContext with mocking factory.
I need this mocking for an Envers RevisionListener, where I get the userName and userId from the SecurityContext created normally by Keycloak.
When calling the Spring beans in the test, mocking works ok.
But when calling the API via TestRestTemplate, SecurityContext is not mocked and is returning a null for all fields (principal, etc).
The original class looks like this:
#SpringBootTest(
classes = SpringBootInitializer.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"keycloak.enabled=false"}
)
#ContextConfiguration(
classes = PersistenceConfiguration.class,
initializers = MyTest.Initializer.class
)
// !!! the SecurityContext mocking will NOT work when calling the controller via REST
#MockKeycloakUser() // do not fail on getting Keycloak data in UserDataRevisionListener
#EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class }) // turn off Spring Security to avoid 401 and 302 responses
#Testcontainers // required to fill #Container fields with containers
#Log4j2
#ActiveProfiles("integration-test")
class MyTest {
#Autowired
private TestRestTemplate restTemplate;
// ...
// call via restTemplate looks like this
private List<MyDTO> executeSearchQuery(String query) {
String searchUrl = getSearchUrl(port, query, filter);
MyDTO[] results = this.restTemplate.getForObject(searchUrl, MyDTO[].class);
return List.of(results);
}
// ...
}
What I used to make the SecurityContext work is:
Add the MockMvc field to the test class.
Add #AutoConfigureMockMvc on the test class.
!!! Execute the API via MockMvc instead of TestRestTemplate
Looks like this:
// all other annotations on the test class stay the same
#AutoConfigureMockMvc // make MockMvc work
// ...
class MyTest {
#Autowired
private MockMvc mockMvc; // trick to make the mock SecurityContext work, which does not work when calling via TestRestTemplate
// Execute the API via mockMvc looks like this:
private String getApiResponse(MyRequest request, int expectedHttpStatus) {
final String url = getRequestUrl();
final String requestBody = JacksonUtils.serializeToString(request);
try {
final MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
.post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody)
;
// use MockMvc instead of TestRestTemplate to successfully use the mock user emulation
return mockMvc
.perform(builder)
.andExpect(status().is(expectedHttpStatus))
.andReturn()
.getResponse()
.getContentAsString(StandardCharsets.UTF_8);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
// ...
}

How to override ITagManager in WeBlog module within Sitecore

I am trying to implement the solution in this answer to be able to restrict the number of tags which show in the tag cloud in WeBlog. Additionally, I am using these instructions from the documentation.
I have modified the WeBlog config to point to my own custom TagManager implementation.
<setting name="WeBlog.Implementation.TagManager" value="My.Namespace.CustomTagManager"/>
If I load sitecore/admin/showconfig.aspx I can confirm the config setting has been updated with the new value.
My CustomTagManager is currently a bare bones implementation of the ITagManager interface.
public class CustomTagManager : ITagManager
{
public string[] GetTagsByBlog(ID blogId)
{
throw new System.NotImplementedException();
}
public string[] GetTagsByBlog(Item blogItem)
{
throw new System.NotImplementedException();
}
public Dictionary<string, int> GetTagsByEntry(EntryItem entry)
{
throw new System.NotImplementedException();
}
public Dictionary<string, int> GetAllTags()
{
throw new System.NotImplementedException();
}
public Dictionary<string, int> GetAllTags(BlogHomeItem blog)
{
throw new System.NotImplementedException();
}
public Dictionary<string, int> SortByWeight(IEnumerable<string> tags)
{
throw new System.NotImplementedException();
}
}
I can reflect the deployed DLL and see these changes have definitely be made, but the changes have no affect. None of the exceptions are thrown and the tag cloud continues to populate as if I'd made no changes at all. It is like the config file change is being completely ignored.
What else do I need to change in order to write my own customer TagManager class?
I am using WeBlog 5.2 and Sitecore 7.1.
After looking at the WeBlog code it was clear that the fallback object was being used and my config change was being ignored.
The cause for this is that WeBlog does:
var type = Type.GetType(typeName, false);
The GetType method only works when the type is found in either mscorlib.dll or the currently assembly. As such, the fix is as simple as providing the assemblies fully qualified name.
<setting name="WeBlog.Implementation.TagManager" value="My.Assembly.CustomTagManager, My.Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
This is the WeBlog code:
private static T CreateInstance<T>(string typeName, Func<T> fallbackCreation) where T : class
{
var type = Type.GetType(typeName, false);
T instance = null;
if (type != null)
{
try
{
instance = (T)Sitecore.Reflection.ReflectionUtil.CreateObject(type);
}
catch(Exception ex)
{
Log.Error("Failed to create instance of type '{0}' as type '{1}'".FormatWith(type.FullName, typeof(T).FullName), ex, typeof(ManagerFactory));
}
}
if(instance == null)
instance = fallbackCreation();
return instance;
}

How do I run my NUnit test cases using Selenium to run against different environments?

I have written NUnit test cases using Selenium to test a web application. And I would like to run the same test cases against different environments (e.g. QA, Staging, & Production) What's the easiest way to achieve that?
NUnit supports parametrised test fixtures as well as parametrised tests. So the first thing is that are you going to want to run specific tests against different environments, or is it the entire test fixture will be rerun for both environments?
I ask because the answer to this determines where you will pass the parameter (the environment). If you are just wanting to rerun the whole test fixture, you should pass the environment in at a test fixture level, that is to create parametrised test fixtures. If you want to run only particular tests against those environment, you'll have to pass it in to each individual test case. An example is below of how I've gone about the same sort of thing:
First create a way to define what 'environment' the tests can 'attach' to. I'd suggest perhaps shoving this into the app.config and have a 'Settings' class and an enum to go with it:
public enum Environment
{
QA,
Production,
Hotfix,
Development
}
public class Settings
{
public static string QAUrl { get { return "some url"; } }
public static string ProductionUrl { get { return "some url"; } }
public static string HotfixUrl { get { return "some url"; } }
public static string DevUrl { get { return "some url"; } }
}
The above "some url" would be read from your configuration file or hardcoded, however you please.
We've now got a concept of an environment, and it's URL, but they are not linked together or related in any way. You would ideally want to give it the 'QA' value of your enum and then it will sort out the URL for you.
Next create a base test fixture that all your test fixtures can inherit from, which keeps hold of the current environment. We also create a Dictionary that now relates the environment value to it's URL:
public class BaseTestFixture
{
private Dictionary<Environment, string> PossibleEnvironments
{
get
{
return new Dictionary<Environment, string>()
{
{ Environment.QA, Settings.QAUrl },
{ Environment.Production, Settings.ProductionUrl },
{ Environment.Hotfix, Settings.HotfixUrl },
{ Environment.Development, Settings.DevelopmentUrl },
}
}
}
private Environment CurrentEnvironment { get; set; }
public BaseTestFixture(Environment environment)
{
CurrentEnvironment = environment;
}
}
You could probably use Reflection to have it work out what URL's map to what enum value's.
So cool, we've got an environment we can run against. A sample test to go to login as an administrator to your site:
public class LoginToSite
{
[Test]
public void CanAdministratorSeeAdministratorMenu()
{
// go to the site
driver.Navigate().GoToUrl("production site");
// login as administrator
}
}
How do we get this to go to the specific URL? Let's modify our base class a little...
public class BaseTestFixture
{
private Dictionary<Environment, string> PossibleEnvironments
{
get
{
return new Dictionary<Environment, string>()
{
{ Environment.QA, Settings.QAUrl },
{ Environment.Production, Settings.ProductionUrl },
{ Environment.Hotfix, Settings.HotfixUrl },
{ Environment.Development, Settings.DevelopmentUrl },
}
}
}
private Environment CurrentEnvironment { get; set; }
protected string CurrentEnvironmentURL
{
get
{
string url;
if (PossibleEnviroments.TryGetValue(CurrentEnviroment, out url))
{
return url;
}
throw new InvalidOperationException(string.Format("The current environment ({0}) is not valid or does not have a mapped URL!", CurrentEnviroment));
}
}
public BaseTestFixture(Environment environment)
{
CurrentEnvironment = environment;
}
public BaseTestFixture()
{
}
}
Our base class now can tell us, depending on what environment we are in, what page to go to...
So we now have this test, inheriting from our base:
public class LoginToSite : BaseTestFixture
{
[Test]
public void CanAdministratorSeeAdministratorMenu()
{
// go to the site
driver.Navigate().GoToUrl(CurrentEnvironmentURL);
// login as administrator
}
}
However, that's great, but the above won't compile...why? We are not actually giving it an environment yet so we must pass one in...
[TestFixture(Environment.QA)]
public class LoginToSite : BaseTestFixture
{
[Test]
public void CanAdministratorSeeAdministratorMenu()
{
// go to the site
driver.Navigate().GoToUrl(CurrentEnvironmentURL);
// login as administrator
}
}
That's great, it now has the environment passed in, the checking of the URL etc are all done in the background for you now...however this still won't compile. Since we are using inheritance, we have to have a constructor to pass it down for us:
public LoginToSite(Environment currentEnvironment)
{
CurrentEnvironment = currentEnvironment;
}
Et voilĂ .
As for specific test cases, this is a little easier, taking our test case from earlier:
public class LoginToSite
{
[TestCase(Environment.QA)]
public void CanAdministratorSeeAdministratorMenu(Environment environment)
{
// go to the site
driver.Navigate().GoToUrl("production site");
// login as administrator
}
}
Which would pass in the environment into that specific test case. You would then need a new Settings class of some sort, to do the environment checking for you (in a similar way as I did before):
public class EnvironmentHelper
{
private static Dictionary<Environment, string> PossibleEnvironments
{
get
{
return new Dictionary<Environment, string>()
{
{ Environment.QA, Settings.QAUrl },
{ Environment.Production, Settings.ProductionUrl },
{ Environment.Hotfix, Settings.HotfixUrl },
{ Environment.Development, Settings.DevelopmentUrl },
}
}
}
public static string GetURL(Environment environment)
{
string url;
if (PossibleEnviroments.TryGetValue(environment, out url))
{
return url;
}
throw new InvalidOperationException(string.Format("The current environment ({0}) is not valid or does not have a mapped URL!", environment));
}
}
Best way would be to use variables instead of hard coded links for all functions. So that it can be changed when needed to change the environment. An easier approach would be to read links from a notepad/excel file .

Http 204 error in REST web service (Jersey)

I am using Jersey/Java to develop my REST services. I need to return an XML representation for my CarStore :
#XmlRootElement
public class CarStore {
private List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
Here is my Car object :
#XmlRootElement
> public class Car {
private String carName;
private Specs carSpecs;
private Category carCategory;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public Specs getCarSpecs() {
return carSpecs;
}
public void setCarSpecs(Specs carSpecs) {
this.carSpecs = carSpecs;
}
public Category getCarCategory() {
return carCategory;
}
public void setCarCategory(Category carCategory) {
this.carCategory = carCategory;
}
}
Specs and Category are enums like this :
#XmlRootElement
> public enum Category {
SEDANS, COMPACTS, WAGONS, HATCH_HYBRIDS, SUVS, CONVERTIBLES, COMPARABLE;
}
My resource class is :
#GET
#Produces({MediaType.APPLICATION_XML})
public CarStore getCars()
{
return CarStoreModel.instance.getAllCars();
}
My jersey client is :
WebResource service = client.resource(getBaseURI());
System.out.println(service.path("rest").path("cars").accept(
MediaType.APPLICATION_XML).get(String.class));
I am getting Http 204 error on access alongwith client exception :
com.sun.jersey.api.client.UniformInterfaceException
Any ideas ? Thanks !
EDIT : I have yet not developed the model class...I just initialized some car objects as dummy data and put them in carstore. Showing all the classes here would be very clumsy.
BTW, sorry for writing 204 Error..it is just that I am getting an Exception that led me think so.
I'm guessing the exception is not related to the response code (204) because 204 is a success condition that indicates "No Content."
I believe you are getting a UniformInterfaceException because your getCars() function is not returning an HTTP response body. The root problem is that your Car List isn't being converted into XML by JAXB because it is missing the #XmlElement annotation.
Your getCars() function should be:
#GET
#Produces(MediaType.APPLICATION_XML)
public CarStore getCars() {
// myCarStore is an instance of CarStore
return myCarStore.getCars();
}
and your Car List in CarStore should be defined:
#XmlElement(name="car")
private List<Car> cars;
Is what you're returning in xml format? I'm not sure what getAllCars does but you can use something like Fiddler to help you view the traffic and see what is being returned to the client and whether its in proper format etc
In your client code, is the resource path correct? Make sure getBaseURI is returning a value.
Perhaps try:
Client client = new Client();
WebResource resource = client.resource(getBaseURI());
CarStore carStore = resource.path("/rest/cars").accept(MediaType.APPLICATION_XML).get(CarStore.class);
Aren't you missing a #Path annotation on your resource class?
#GET
#Path("cars")
#Produces({ MediaType.APPLICATION_XML })
public CarStore getCars() {
return CarStoreModel.instance.getAllCars();
}
Check if the URL at which your REST WS is mounted the one you expect by putting a breakpoint in your getCars() method (or putting a System.out.println) to make sure it actually gets called.
It seems there is a hard coded check in Jersey to throw a UniformInterfaceException when a HTTP 204 is returned.
The best solution will be to 'fix' the rest server so it never returns a null. e.g. return an Empty list or a Class with not values set.
Else you will need to catch UniformInterfaceException which is really ugly
if (getStatus() == 204) {
throw new UniformInterfaceException(this);
}
More info here :
http://grepcode.com/file/repo1.maven.org/maven2/com.sun.jersey/jersey-client/1.17.1/com/sun/jersey/api/client/ClientResponse.java#ClientResponse.getEntity%28java.lang.Class%2Cjava.lang.reflect.Type%29