PrimitiveResourceTypeMap throws exception when trying to use EF as data feed - entity-framework

Short description:
I'm trying to create a WFC data service that will use entity framework to retrieve data from db. The important thing is that the service must be hosted inside sharepoint server. Everything (almost) is ok except that when I'm trying to access deployed service from sharepoint I've got an exception:
The server encountered an error processing the request. The exception message is 'The type initializer for 'System.Data.Services.Providers.PrimitiveResourceTypeMap' threw an exception.'. See server logs for more details. The exception stack trace is:
at System.Data.Services.Providers.PrimitiveResourceTypeMap.get_TypeMap() at System.Data.Services.Providers.ObjectContextServiceProvider.PopulateMetadata(ProviderMetadataCacheItem metadataCacheItem) at System.Data.Services.Providers.BaseServiceProvider.LoadMetadata(Boolean skipServiceOperations) at System.Data.Services.Providers.EntityFrameworkDataService1.CreateInternalProvider(Object dataSourceInstance) at System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider& metadataProviderInstance, IDataServiceQueryProvider& queryProviderInstance, Object& dataSourceInstance, Boolean& isInternallyCreatedProvider) at System.Data.Services.DataService1.CreateProvider() at System.Data.Services.DataService1.HandleRequest() at System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) at SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
The same service hosted from normal web app works fine.
Is there anyone that had similar issue and has some clues?

I managed to create fully functional WCF data service hosted inside SharePoint 2013 on premise. I got the exception mentioned in question (as well as many others).
By fully functional I mean that my odata requests with filters from CSOM and java script are properly executed and (auto-magically) results in properly formed queries to SQL server database. Works both http and https.
Here is short description what is necessary to have it all working.
A bunch of dll from nuget needs to be deployed to GAC via SharePoint WSP (here is list which worked for me)
a. EntityFramework.dll 6.1.3 for .Net 4.5
b. EntityFramework.SqlServer.dll 6.1.3 for .Net 4.5
c. Microsoft.Data.Edm.dll 5.6.2
d. Microsoft.Data.OData.dll 5.6.2
e. Microsoft.Data.Services.dll 5.6.2
f. Microsoft.Data.Services.Client.dll 5.6.2
g. Microsoft.OData.EntityFrameworkProvider.dll 1.0.0-beta2
h. System.Spatial.dll 5.6.2
Note: The trick is that there is no direct error that some of these dll’s are missing. The exception from question is displayed when there was no System.Spatial.dll in GAC.
Service should look similar to above:
using System.Data.Services;
using System.Data.Services.Providers;
using System.ServiceModel.Activation;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class yourService : EntityFrameworkDataService<YourEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = System.Data.Services.Common.DataServiceProtocolVersion.V3;
}
}
Svc file: YourService.svc should be deployed to dedicated feature folder inside ISAPI SP folder
For http – fragment:
<service behaviorConfiguration="WCFServicesBehavior" name=" Namespace.yourservice ">
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
For https: like in http but use mexHttpsBinding binding
Open your endpoint in browser to check if this is working
http://yoursite.local/_vti_bin/name_of_your_feature/yourservice.svc - should return info about service
http://yoursite.local/_vti_bin/name_of_your_feature/yourservice.svc/Name_of_your_entitySet() – should return all entities of given type
Check in SQL Server Profiler if your odata filters are properly translated to SQL queries

Related

EF Core Power Tools EntityFrameworkCore.Design.OperationException suddenly occurring on "Add DbContext Diagram"

I've been using EF Core Power Tools to assist with learning EF Core. The data project is simply a class library that contains the base DbContext used by the associated web app, plus the migrations folder.
It's been working fine until suddenly this error occurs when I "Add DbContext Diagram"
System.InvalidOperationException: Error:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EventFinderContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[EventFinderData.EventFinderContext]' while attempting to activate 'EventFinderData.EventFinderContext'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Modelling.EfCoreModelBuilder.BuildResult(String outputPath, String startupOutputPath, Boolean generateDdl) in C:\Code\EFCorePowerTools\src\GUI\efpt30.core\EFCoreModelBuilder.cs:line 41
at Modelling.Program.Main(String[] args) in C:\Code\EFCorePowerTools\src\GUI\efpt30.core\Program.cs:line 56
at async Task EFCorePowerTools.Handlers.ModelAnalyzerHandler.GenerateAsync(string outputPath, Project project, GenerationType generationType)
I'm not sure even where to start looking to investigate, so any pointers would be appreciated please. The solution builds okay, the database seems fine, and the associated Blazor project also runs fine.
Not sure if its helpful but in my data project, the constructor for the DbContext is this:
namespace EventFinderData
{
public class EventFinderContext : DbContext
{
public EventFinderContext(DbContextOptions<EventFinderContext> options) : base(options)
{
}
}
}
You have to register EventFinderContext in program.cs
builder.Services.AddDbContext<EventFinderContext>(
opt => opt.UseSqlServer("Your_connection_string"));
As advised by ErikEJ (the author of Power Tools) the diagram function only works on the executable project. Once I had added a web application project to my solution, the original console and data layer projects in that solution no longer worked for creating the diagram.

HelloWorld using Drools Workbench & KIE Server

Have KIE Drools Workbench 6.2.0 Final installed inside a JBoss 7 Application Server local instance and Kie Server 6.2.0 Final inside a local Tomcat 7 instance.
Using the web based KIE Workbench strictly for evaluation purposes (am using it to code generate Java based Maven projects and am not using a particular IDE such as Eclipse or IntelliJ IDEA):
Created a new repository called testRepo
Created a new project called HelloWorld
Created a new Data Object called HelloWorld with a String property called message:
package demo;
/**
* This class was automatically generated by the data modeler tool.
*/
public class HelloWorld implements java.io.Serializable {
static final long serialVersionUID = 1L;
private java.lang.String message;
public HelloWorld()
{
}
public java.lang.String getMessage()
{
return this.message;
}
public void setMessage(java.lang.String message)
{
this.message = message;
}
public HelloWorld(java.lang.String message)
{
this.message = message;
}
}
Created a new DRL containing the following contents:
package demo;
import demo.HelloWorld;
rule "hello"
when
HelloWorld(message == "Joe");
then
System.out.println("Hello Joe!");
end
When I deploy it to my Kie Server under this URL:
http://localhost:8080/kie-server-6.2.0.Final-webc/services/rest/server/containers/helloworld
I get the following response when I copy and paste the above URL in Google Chrome:
<response type="SUCCESS" msg="Info for container hello">
<kie-container container-id="hello" status="STARTED">
<release-id>
<artifact-id>Hello</artifact-id>
<group-id>demo</group-id>
<version>1.0</version>
</release-id>
<resolved-release-id>
<artifact-id>Hello</artifact-id>
<group-id>demo</group-id>
<version>1.0</version>
</resolved-release-id>
<scanner status="DISPOSED"/>
</kie-container>
</response>
When I try to do a POST using the following payload (using Postman or SoapUI):
<batch-execution lookup="defaultKieSession">
<insert out-identifier="message" return-object="true" entrypoint="DEFAULT">
<demo.HelloWorld>
<message>Joe</message>
<demo.HelloWorld>
</insert>
Received the following:
HTTP Status 415 - Cannot consume content type
type Status report
message Cannot consume content type
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
What am I possibly doing wrong? I went to Deploy -> Rule Deployments and registered my kie-server along with creating a container called helloworld and as one can see from Step # 5, it worked. Perhaps I am not deploying it correctly?
Btw, I used the following Stack Overflow post as a basis (prior to asking this question)...
Most of the search results from Google just explain how to programmatically create Drools projects by setting up Maven based projects. Am evaluating KIE Drools Workbench to see how easily a non-technical person can use KIE Drools Workbench to generate Drools based rules and execute them.
Am I missing a step? Under Tomcat 7, it only contains the following directories under apache-tomcat-7.0.64/webapps/kie-server-6.2.0.Final-webc:
META-INF
WEB-INF
Thanks for taking the time to read this...
What content type are you using in your POST request header?
As far as I remember, that error message happened if you didn't provide a content-type: application/xml in your request's header.
Hope it helps,
are you ok?
The response of Esteban is right, but, you should add a another header, the header that you need to add is "Authorization", and the value of Authorization is the user that you registered to you application realm to your kie-server converted in base64. e.g.:
kieserver:system*01
converted to base64:
a2llc2VydmVyOnN5c3RlbSowMQ==
Anyway, the complete header of my request is like this:
Authorization : Basic a2llc2VydmVyOnN5c3RlbSowMQ==
Content-Type : application/xml
I hope it was helpful.
Sorry for my english! :)
I got it working with using Postman (Chrome app / plugin) with the Authorization tab selected to No Auth. Really cool response!
<response type="SUCCESS" msg="Container helloworld successfully called.">
<results>
<![CDATA[<execution-results>
<result identifier="message">
<demo.HelloWorld>
<message>Joe</message>
</demo.HelloWorld>
</result>
<fact-handle identifier="message" external-form="0:4:1864164041:1864164041:4:DEFAULT:NON_TRAIT"/>
</execution-results>]]>
</results>
</response>

Xamarin PCL Unhandled Exception: TargetInvocationException

Im making an mobile application which can communicate with Dynamics AX using a WCF service.
Im fairly new to Xamarin, and im trying to create a PCL library for a shared IOS and Android application. Im also working on an Windows Phone App which pretty much works by now. Im using a WCF service ive created which does all the communication with Dynamics AX, and the service exposes its methods using Metadata. I've added a Service Reference to the Windows Phone solution and the generated Proxy works like a charm, i should say im using SOAP.
But if i transfer the generated Reference.cs file to my Xamarin PCL project and call my method the exact same way i get the following error:
Unhandled Exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.Serialization.SerializationException: Expected element 'ExceptionDetail' in namespace 'http://schemas.datacontract.org/2004/07/System.ServiceModel', but found Element node 'AifFault' in namespace 'http://schemas.microsoft.com/dynamics/2008/01/documents/Fault'
at System.Runtime.Serialization.XmlFormatterDeserializer.Deserialize (System.Xml.XmlReader reader, System.Type declaredType, System.Runtime.Serialization.KnownTypeCollection knownTypes, IDataContractSurrogate surrogate, System.Runtime.Serialization.DataContractResolver resolver, System.Runtime.Serialization.DataContractResolver defaultResolver, System.String name, System.String ns, Boolean verifyObjectName) [0x0003e] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/7.4.0.108/src/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/XmlFormatterDeserializer.cs:63
at System.Runtime.Serialization.DataContractSerializer.ReadObject (System.Xml.XmlDictionaryReader reader, Boolean verifyObjectName) [0x00024] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/7.4.0.108/src/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs:363
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject (System.Xml.XmlDictionaryReader reader) [0x00000] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/7.4.0.108/src/mono/mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/XmlObjectSerializer.cs:76
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters) [0x0019b] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/7.4.0.108/src/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:550
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00038] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/7.4.0.108/src/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:496
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x0001c] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/7.4.0.108/src/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:477
--- End of inner exception stack trace ---
The issue only occurs when AX return an AIFFault Exception and for some reason it cant be caught by Xamarin.. Its caught just fine in Visual Studio in Windows Phone.
Here is the code from making the call:
try{
var result = await _service.ExecuteGetMethod(MyRecord)
}
catch(FaultException fe){
ShowError(fe);
}
This works just fine, and the error message from AX is showed in fe.Message, but running the exact same in Xamarin gives me the above error.
Do i need to add AIFFault somewhere in my WCF service for clients to be able to see it?

Code-First Entity Framework - error creating SQL CE DB

I have been using Entity Framework CTP with Code-First as in this tutorial by Scott Guthrie and another by Scott Hanselman (can't post the link, but google "Simple Code First with Entity Framework 4 - Magic Unicorn Feature CTP 4"). This is working perfectly for the main MVC application, but I am now trying to add a testing project, that uses a separate SQL CE Database.
I have added the following to the App.Config file:
<connectionStrings>
<add name="MyData"
connectionString="Data Source=D:\myProject\myDb.sdf;"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
However when I try to run the tests it throws the following error when trying to create the database:
Test method
MyProjet.Tests.Administration.ModlelTests.Business.TestGetBusinessesList
threw exception:
System.Reflection.TargetInvocationException:
Exception has been thrown by the
target of an invocation. --->
System.TypeInitializationException:
The type initializer for
'System.Data.SqlServerCe.SqlCeProviderServices'
threw an exception. --->
System.Security.VerificationException:
Operation could destabilize the
runtime.
With the following stack trace:
System.Data.SqlServerCe.SqlCeProviderServices..ctor()
System.Data.SqlServerCe.SqlCeProviderServices..cctor()
System.RuntimeFieldHandle.GetValue(RtFieldInfo
field, Object instance, RuntimeType
fieldType, RuntimeType declaringType,
Boolean& domainInitialized)
System.Reflection.RtFieldInfo.InternalGetValue(Object
obj, Boolean doVisibilityCheck,
Boolean doCheckConsistency)
System.Reflection.RtFieldInfo.InternalGetValue(Object
obj, Boolean doVisibilityCheck)
System.Reflection.RtFieldInfo.GetValue(Object
obj)
System.Data.SqlServerCe.ExtensionMethods.SystemDataSqlServerCeSqlCeProviderServices_Instance_GetValue()
System.Data.SqlServerCe.ExtensionMethods.SystemDataSqlServerCeSqlCeProviderServices_Instance()
System.Data.SqlServerCe.SqlCeProviderFactory.System.IServiceProvider.GetService(Type
serviceType)
System.Data.Common.DbProviderServices.GetProviderServices(DbProviderFactory
factory)
System.Data.Common.DbProviderServices.GetProviderServices(DbConnection
connection)
System.Data.Entity.ModelConfiguration.Internal.Configuration.CodeFirstCachedMetadataWorkspace.GetMetadataWorkspace(DbConnection
storeConnection)
System.Data.Entity.Infrastructure.DbModel.CreateObjectContext[TContext](DbConnection
existingConnection)
System.Data.Entity.Internal.LazyInternalContext.InitializeFromModel(DbModel
model)
System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
System.Data.Entity.Internal.InternalContext.Initialize()
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type
entityType)
System.Data.Entity.Internal.Linq.EfInternalQuery1.Initialize()
System.Data.Entity.Internal.Linq.EfInternalQuery1.Include(String
path)
System.Data.Entity.Infrastructure.DbQuery`1.Include(String
path)
MyProjet.Areas.Administration.Models.BusinessModel.GetBusinesses()
in
D:\projects2010\MyProjet\MyProjet\Areas\Administration\Models\BusinessModel.cs:
line 47
MyProjet.Tests.Administration.ModlelTests.Business.TestGetBusinessesList()
in
D:\projects2010\MyProjet\MyProjet.Tests\Administration\ModlelTests\Business.cs:
line 45
I have tried replacing the existing MyData connection string in the MVC application, and it works fine. It only causes this problem when this is added to the Testing project. Additionally the testing project works without problem when pointed at an SQL or SQL Express Database.
Have been struggling with this for a while now, and just can't figure it out. I am sure I have overlooked something simple.
Try using
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
See my blog post for an example http://www.arrangeactassert.com/code-first-entity-framework-unit-test-examples/
I have been running the tests under the Built in Microsoft testing framework. Changing the test framework to NUnit (as in Jag's tutorial) has fixed the problem.
So looks like there is a conflict between SqlServerCe and the Visual Studio Unit Testing Framework.

Correct way to make datasources/resources a deploy-time setting

I have a web-app that requires two settings:
A JDBC datasource
A string token
I desperately want to be able to deploy one .war to various different containers (jetty,tomcat,gf3 minimum) and configure these settings at application level within the container.
My code does this:
InitialContext ctx = new InitialContext();
Context envCtx = (javax.naming.Context) ctx.lookup("java:comp/env");
token = (String)envCtx.lookup("token");
ds = (DataSource)envCtx.lookup("jdbc/datasource")
Let's assume I've used the glassfish management interface to create two jdbc resources: jdbc/test-datasource and jdbc/live-datasource which connect to different copies of the same schema, on different servers, different credentials etc. Say I want to deploy this to glassfish with and point it at the test datasource, I might have this in my sun-web.xml:
...
<resource-ref>
<res-ref-name>jdbc/datasource</res-ref-name>
<jndi-name>jdbc/test-datasource</jndi-name>
</resource-ref>
...
but
sun-web.xml goes inside my war, right?
surely there must be a way to do this through the management interface
Am I even trying to do the right thing? Do other containers make this any easier? I'd be particularly interested in how jetty 7 handles this since I use it for development.
EDIT Tomcat has a reasonable way to do this:
Create $TOMCAT_HOME/conf/Catalina/localhost/webapp.xml with:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="false" privileged="true">
<!-- String resource -->
<Environment name="token" value="value of token" type="java.lang.String" override="false" />
<!-- Linking to a global resource -->
<ResourceLink name="jdbc/datasource1" global="jdbc/test" type="javax.sql.DataSource" />
<!-- Derby -->
<Resource name="jdbc/datasource2"
type="javax.sql.DataSource"
auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDataSource"
url="jdbc:derby:test;create=true"
/>
<!-- H2 -->
<Resource name="jdbc/datasource3"
type="javax.sql.DataSource"
auth="Container"
driverClassName="org.h2.jdbcx.JdbcDataSource"
url="jdbc:h2:~/test"
username="sa"
password=""
/>
</Context>
Note that override="false" means the opposite. It means that this setting can't be overriden by web.xml.
I like this approach because the file is part of the container configuration not the war, but it's not part of the global configuration; it's webapp specific.
I guess I expect a bit more from glassfish since it is supposed to have a full web admin interface, but I would be happy enough with something equivalent to the above.
For GF v3, you may want to try leveraging the --deploymentplan option of the deploy subcommand of asadmin. It is discussed on the man page for the deploy subcommand.
We had just this issue when migrating from Tomcat to Glassfish 3. Here is what works for us.
In the Glassfish admin console, configure datasources (JDBC connection pools and resources) for DEV/TEST/PROD/etc.
Record your deployment time parameters (in our case database connect info) in properties file. For example:
# Database connection properties
dev=jdbc/dbdev
test=jdbc/dbtest
prod=jdbc/dbprod
Each web app can load the same database properties file.
Lookup the JDBC resource as follows.
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* #param resourceName the resource name of the connection pool (eg jdbc/dbdev)
* #return Connection a pooled connection from the data source
* associated with resourceName
* #throws NamingException will be thrown if resource name is not found
*/
public Connection getDatabaseConnection(String resourceName)
throws NamingException, SQLException {
Context initContext = new InitialContext();
DataSource pooledDataSource = (DataSource) initContext.lookup(resourceName);
return pooledDataSource.getConnection();
}
Note that this is not the usual two step process involving a look up using the naming context "java:comp/env." I have no idea if this works in application containers other than GF3, but in GF3 there is no need to add resource descriptors to web.xml when using the above approach.
I'm not sure to really understand the question/problem.
As an Application Component Provider, you declare the resource(s) required by your application in a standard way (container agnostic) in the web.xml.
At deployment time, the Application Deployer and Administrator is supposed to follow the instructions provided by the Application Component Provider to resolve external dependencies (amongst other things) for example by creating a datasource at the application server level and mapping its real JNDI name to the resource name used by the application through the use of an application server specific deployment descriptor (e.g. the sun-web.xml for GlassFish). Obviously, this is a container specific step and thus not covered by the Java EE specification.
Now, if you want to change the database an application is using, you'll have to either:
change the mapping in the application server deployment descriptor - or -
modify the configuration of the existing datasource to make it points on another database.
Having an admin interface doesn't really change anything. If I missed something, don't hesitate to let me know. And just in case, maybe have a look at this previous answer.