REST Web API post related entities - asp.net-web-api

Hi CodeFluent enthusiasts!
I have these two related entities in my model:
<cf:entity name="Main" defaultUsePersistenceDefaultValue="false" namespace="idscommerce" categoryPath="/idscommerce">
<cf:property name="Id" key="true" />
<cf:property name="Nom" />
<cf:property name="Ordre" />
<cf:property name="URL" />
<cf:property name="Icona" />
<cf:property name="Texts" typeName="{0}.MainTextCollection" relationPropertyName="Main" dataMember="true" />
<cf:entity name="MainText" defaultUsePersistenceDefaultValue="false" namespace="idscommerce" categoryPath="/idscommerce">
<cf:property name="Id" key="true" />
<cf:property name="Text" />
<cf:property name="Idioma" typeName="{0}.Idioma" relationPropertyName="MainTexts" />
<cf:property name="Main" typeName="{0}.Main" relationPropertyName="Texts" />
In my API, GET is working right, but when I POST (I'm using the [FromBody]Main value option) it goes into a loop at LoadByMain method from MainTextCollection.
// GET api/Main/id
public Main Get(string id)
{
idscommerce.Main value = idscommerce.Main.LoadByEntityKey(id);
if(value == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return value;
}
// POST api/Main
public HttpResponseMessage Post([FromBody]Main value)
{
if(value == null || !value.Save())
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, value);
}
What it's weird is that the same class works as expected when calling from Main.LoadAll() or Main.LoadById(id), but it's going into an endless loop when called from the API POST method using Post([FromBody]Main value).

Related

How to combine token Authenication and CRSF?

I am developing a web application with consist of the following
Rest Web service (Spring 4) | JWT token authentication
Web pages (login.xhtml, index.xhtml) (JSF, primeface) | crsf
The problem I am facing now is weird.
If my spring security is enabled, any access to rest web services need to be authenticated before the access is granted. I am using JWT token authentication for my login. However my web pages will fail after I login. i.e my login is successful but any action after this, results in an invalid crsf token or null request error.
If my spring security is disabled, my rest services does not need to be authenticated to access the web services but my web pages works perfectly fine.
How do I integrate both solutions together?
All my web pages already included the following:
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
ApplicationContext-Security.xml:
<http pattern="/auth/login" security="none" />
<http pattern="/login.xhtml" security="none" />
<http pattern="/index.xhtml" security="none" />
<http pattern="/javax.faces.resource/**" security="none" />
<http pattern="/RES_NOT_FOUND" security="none" />
<http pattern="/img/**" security="none" />
<sec:http auto-config="false" create-session="stateless" entry-point-ref="customEntryPoint" use-expressions="true">
<intercept-url pattern="/admin/**" access="hasRole('ADMIN') or hasRole('HQ')" />
<intercept-url pattern="/audit/**" access="hasRole('ADMIN')" />
<intercept-url pattern="/request/**" access="hasRole('ADMIN') or hasRole('HQ')" />
<intercept-url pattern="/reporting/**" access="hasRole('ADMIN') or hasRole('HQ')" />
<sec:custom-filter ref="customAuthenticationFilter"
before="PRE_AUTH_FILTER" />
<!-- <sec:csrf disabled="true" /> -->
</sec:http>
As you can see i included the <http pattern="/index.xhtml" security="none" /> so that i can allow what feature that is in my index.xhtml to work. But now i can access the index.xhtml directly.
Can someone advise on how to fix this?
===== EDITED. MORE INFO =====
To add on, this is my login page and controller.
login.xhtml:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>BTS Upload</title>
<h:outputStylesheet library="css" name="bootstrap.min.css" />
<h:outputScript library="js" name="jquery-1.11.1.min.js" />
<h:outputScript library="js" name="bootstrap.min.js" />
</h:head>
<!-- Css here -->
<h:body>
<font color="red"> <h:outputLabel
value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</font>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-md-offset-4">
<h1 class="text-center login-title">Sign in</h1>
<div class="account-wall">
<h:graphicImage class="profile-img" library="images"
name="photo.png" />
<h:form class="form-signin">
<h:outputLabel value="Enter UserName:" />
<h:inputText id="username" value="#{loginAction.username}"
required="true" requiredMessage="Please enter your username"
autofocus="true" class="form-control"></h:inputText>
<h:message for="username" id="msg"
errorStyle="color:red; display:block" />
<br />
<h:outputLabel value="Enter Password:" />
<h:inputSecret id="password" value="#{loginAction.pwd}"
required="true" requiredMessage="Please enter your password"
class="form-control"></h:inputSecret>
<h:message for="password" id="msg1"
errorStyle="color:red; display:block" />
<br />
<br />
<h:commandButton class="btn btn-lg btn-primary btn-block"
action="#{loginAction.login}"
value="Login"></h:commandButton>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</h:form>
</div>
</div>
</div>
</div>
</h:body>
</html>
Controller:
#ManagedBean(name="loginAction")
#SessionScoped
public class LoginAction extends BaseAction implements Serializable
{
private static final long serialVersionUID = 1094801825228386363L;
private String pwd;
private String msg;
private String username;
#ManagedProperty("#{accessControlService}")
private AccessControlService accessControlService;
public String getPwd()
{
return pwd;
}
public void setPwd(String pwd)
{
this.pwd = pwd;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public String getUsername()
{
return username;
}
public void setUsername(String user)
{
this.username = user;
}
//validate login and redirect to the specified website.
public String login()
{
System.out.println();
System.out.println("Call Log in");
if (username.equals("") || pwd.equals(""))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Password", "Please enter correct username and Password"));
return "login";
}
boolean valid = false;
String token = "";
try
{
token = accessControlService.isAuthorizedUser(username, pwd, PropertiesUtil.LoginType.WEB_BTS.ordinal(), this.getRequest());
}
catch (Exception e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Error", e.getLocalizedMessage()));
}
if(token.contains(PropertiesUtil.TOKEN_HEADER))
{
valid = true;
}
if (valid)
{
HttpSession session = this.getSession();
session.setAttribute("username", username);
session.setAttribute("token", token);
return "admin";
}
else
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Password", "Please enter correct username and Password"));
return "login";
}
}
// logout event, invalidate session
public String logout()
{
System.out.println("**********************************************************");
try
{
accessControlService.logout(getUsername(), PropertiesUtil.LoginType.WEB_BTS.ordinal(), getRequest());
HttpSession session = this.getSession();
session.invalidate();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "login";
}
public AccessControlService getAccessControlService()
{
return accessControlService;
}
public void setAccessControlService(AccessControlService accessControlService)
{
this.accessControlService = accessControlService;
}
}
Firstly you must be sure that you have spring security 4 compatible *-security.xml and *-servlet.xml look at this
From part of security.xml that you posted I can see that you don't have form-login tag. It should be something like this
<security:form-login default-target-url="/index"
login-page="/login"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?login_error=1"/>
Your login jsp needs to have action j_spring_security_check to trigger filter chain:
<form action="<c:url value="/j_spring_security_check"/>" method="POST"> ...
You don't need csrf hidden input because spring automatically injects it into request header and parameters (if you don't disable it) as of spring 4

JSP kendo grid EDIT /ADD Handle ERROR response from spring rest Kendo UI v2015.3.1111

Trying Kendo UI JSP editable grid. Grid is working with few problems.
(Version : Kendo UI v2015.3.1111 )
Export: Even with allPages="allPages", its exporting only current
page.
After CREATE, GRID is not updated with server response which has user createDate. Same with Update, grid not updated with update date
even though the updated user object is passed.
Grid shows user added even if it failed in the backend. How to handle error response for create /update and show the failed message ?
Any help greatly appreciated.
Controller create part:
#RequestMapping(value = "/user/create", method = RequestMethod.POST)
public #ResponseBody User create(#RequestBody Map<String, Object> model) {
log.debug("create");
User target = new User();
target.setUserName((String)model.get("UserName"));
target.setFirstName((String)model.get("firstName"));
target.setLastName((String)model.get("lastName"));
target.setOpenDate(getDateFromStr((String)model.get("openDate")));
target.setEditDate(getDateFromStr((String)model.get("editDate")));
User user = userDao.createUser(target);
log.info("user"+user.getUserId()+user.getOpenDate());
return user;
}
JSP PART:
<c:url value="/user/create" var="createUrl" />
<c:url value="/user/read" var="readUrl" />
<c:url value="/user/update" var="updateUrl" />
<c:url value="/user/destroy" var="destroyUrl" />
<c:url value="/user/saveexcel" var="saveExcelUrl" />
<c:url value="/user/savepdf" var="savePdfUrl" />
<kendo:grid name="grid" pageable="true" sortable="true" height="750px" filterable="true">
<kendo:grid-scrollable/>
<kendo:grid-pdf fileName="KendoUIGridExport.pdf" allPages="allPages" proxyURL="${savePdfUrl}"/>
<kendo:grid-excel fileName="KendoUIGridExport.xlsx" allPages="allPages" proxyURL="${saveExcelUrl}" />
<kendo:grid-editable mode="popup" confirmation="Are you sure you want to remove this item?"/>
<kendo:grid-toolbar>
<kendo:grid-toolbarItem name="create"/>
<kendo:grid-toolbarItem name="excel"/>
<kendo:grid-toolbarItem name="pdf"/>
</kendo:grid-toolbar>
<kendo:grid-columns>
<kendo:grid-column title="User Name" field="userName" width="120px"/>
<kendo:grid-column title="First Name" field="firstName" width="120px" />
<kendo:grid-column title="Last Name" field="lastName" width="120px" />
<kendo:grid-column title="Open Date" field="openDate" width="120px" format="{0:MM/dd/yyyy}" />
<kendo:grid-column title="Edit Date" field="editDate" width="120px" format="{0:MM/dd/yyyy}" />
<kendo:grid-column title=" " width="150px">
<kendo:grid-column-command>
<kendo:grid-column-commandItem name="edit" />
<kendo:grid-column-commandItem name="destroy" />
</kendo:grid-column-command>
</kendo:grid-column>
</kendo:grid-columns>
<kendo:dataSource pageSize="10" serverPaging="false" serverSorting="false" serverFiltering="false" serverGrouping="false" >
<kendo:dataSource-transport>
<kendo:dataSource-transport-create url="${createUrl}" type="POST" dataType="json" contentType="application/json"/>
<kendo:dataSource-transport-read url="${readUrl}" type="POST" dataType="json" contentType="application/json"/>
<kendo:dataSource-transport-update url="${updateUrl}" type="POST" dataType="json" contentType="application/json" />
<kendo:dataSource-transport-destroy url="${destroyUrl}" type="POST" dataType="json" contentType="application/json" />
<kendo:dataSource-transport-parameterMap>
<script>
function parameterMap(options,type) {
return JSON.stringify(options);
}
</script>
</kendo:dataSource-transport-parameterMap>
</kendo:dataSource-transport>
<kendo:dataSource-schema>
<kendo:dataSource-schema-model id="userId">
<kendo:dataSource-schema-model-fields>
<kendo:dataSource-schema-model-field name="userName" type="string" >
<kendo:dataSource-schema-model-field-validation required="true" />
</kendo:dataSource-schema-model-field>
<kendo:dataSource-schema-model-field name="firstName" type="string">
<kendo:dataSource-schema-model-field-validation required="true" />
</kendo:dataSource-schema-model-field>
<kendo:dataSource-schema-model-field name="lastName" type="string">
<kendo:dataSource-schema-model-field-validation required="true" />
</kendo:dataSource-schema-model-field>
<kendo:dataSource-schema-model-field name="openDate" type="date" editable="false" />
<kendo:dataSource-schema-model-field name="editDate" type="date" editable="false"/>
</kendo:dataSource-schema-model-fields>
</kendo:dataSource-schema-model>
</kendo:dataSource-schema>
</kendo:dataSource>
</kendo:grid>
Resolved myself: For pdf, allPages="true" works.
Grid refresh: FOR requestEnd event
function onRequestEnd(e) {
if (e.type == "create") {
e.sender.read();
}
else if (e.type == "update") {
e.sender.read();
}
}

Navigation property values not added to entity

I've a WebAPI OData v3 (5.6.3) service (without EF) which I call from breeze using server side metadata. Unfortunately I cannot get navigation properties to load correctly in breeze.
The model is defined as following:
public class ParentItem
{
private readonly List<ChildItem> childItems = new List<ChildItem>();
[Key]
public int Id { get; set; }
public virtual ICollection<ChildItem> ChildItems
{
get
{
return this.childItems;
}
}
#endregion
}
public class ChildItem
{
[Key]
public int Id { get; set; }
[ForeignKey("ParentItem")]
public int? ParentItemId { get; set; }
public virtual ParentItem ParentItem { get; set; }
}
These are the metadata generated by the server:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
<edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<Schema Namespace="Solutions2Share.Solutions.MeetingManagerWeb.Models" xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
<EntityType Name="ParentItem">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false" />
<NavigationProperty Name="ChildItems" Relationship="MyNamespace_ChildItem_ChildItemsPartner" ToRole="ChildItems" FromRole="ChildItemsPartner" />
</EntityType>
<EntityType Name="ChildItem">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false" />
<Property Name="ParentId" Type="Edm.Int32" />
<NavigationProperty Name="ParentItem" Relationship="MyNamespace_ParentItem_ParentItemPartner" ToRole="ParentItem" FromRole="ParentItemPartner" />
</EntityType>
<Association Name="MyNamespace_ChildItem_ChildItemsPartner">
<End Type="MyNamespace.ChildItem" Role="ChildItems" Multiplicity="*" />
<End Type="MyNamespace.ParentItem" Role="ChildItemsPartner" Multiplicity="0..1" />
</Association>
<Association Name="MyNamespace_ParentItem_ParentItemPartner">
<End Type="MyNamespace.ParentItem" Role="ParentItem" Multiplicity="0..1" />
<End Type="MyNamespace.ChildItem" Role="ParentItemPartner" Multiplicity="0..1" />
</Association>
<EntityContainer Name="Container" m:IsDefaultEntityContainer="true">
<EntitySet Name="ParentItems" EntityType="MyNamespace.ParentItem" />
<EntitySet Name="ChildItems" EntityType="MyNamespace.ChildItem" />
<AssociationSet Name="MyNamespace_ChildItem_ChildItemsPartnerSet" Association="MyNamespace_ChildItem_ChildItemsPartner">
<End Role="ChildItemsPartner" EntitySet="ParentItems" />
<End Role="ChildItems" EntitySet="ChildItems" />
</AssociationSet>
<AssociationSet Name="MyNamespace_ParentItem_ParentItemPartnerSet" Association="MyNamespace_ParentItem_ParentItemPartner">
<End Role="ParentItemPartner" EntitySet="ChildItems" />
<End Role="ParentItem" EntitySet="ChildItems" />
</AssociationSet>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>
I'm using webApiOData on the client:
breeze.config.initializeAdapterInstance('dataService', 'webApiOData', true);
The query which I'm execute looks like this:
breeze.EntityQuery().from('ParentItems').expand('ChildItems');
The server call returns the correct items:
{
"odata.metadata":"http://example.com/api/$metadata#ParentItems","value":[
{
"odata.type":"MyNamespace.ParentItem","odata.id":"http://example.com/api/ParentItems(1)","ChildItems#odata.navigationLinkUrl":"http://example.com/api/ParentItems(1)/ChildItems","ChildItems":[
{
"odata.type":"MyNamespace.ChildItem","odata.id":"http://example.com/api/ChildItems(1)","ParentItem#odata.navigationLinkUrl":"http://example.com/api/ChildItems(1)/ParentItem","Id":1,"ParentItemId":1
},{
"odata.type":"MyNamespace.ChildItem","odata.id":"http://example.com/api/ChildItems(2)","ParentItem#odata.navigationLinkUrl":"http://example.com/api/ChildItems(2)/ParentItem","Id":2,"ParentItemId":1
}
],"Id":1
}
]
}
But the ChildItems property of the ParentItem entity is empty.
Edit: If I call manager.getEntities()after executing the query all parent and child items are returned.

how to get the string value and save it in database

I am using spring form tags and hibernate..
my jsp page has the follwoing code:
<tr><td><form:input path="userEnteredHostNameString" size="30" maxlength="200"/></td>
<td><form:input path="userEnteredDirectoryString" size="30" maxlength="200"/></td>
<td><form:input path="userEnteredUserNameString" size="20" maxlength="20"/></td>
<td><form:input path="userEnteredPasswordString" size="20" maxlength="20"/></td></tr>
getters and setters in my location.java
public String getUserEnteredHostNameString() {
return userEnteredHostNameString;
}
public void setUserEnteredHostNameString(String userEnteredHostNameString) {
if (userEnteredHostNameString!=null) userEnteredHostNameString = userEnteredHostNameString.toUpperCase();
this.userEnteredHostNameString = userEnteredHostNameString;
}
public String getUserEnteredDirectoryString() {
return userEnteredDirectoryString;
}
public void setUserEnteredDirectoryString(String userEnteredDirectoryString) {
if (userEnteredDirectoryString!=null) userEnteredDirectoryString = userEnteredDirectoryString.toUpperCase();
this.userEnteredDirectoryString = userEnteredDirectoryString;
}
public String getUserEnteredUserNameString() {
return userEnteredUserNameString;
}
public void setUserEnteredUserNameString(String userEnteredUserNameString) {
if (userEnteredUserNameString!=null) userEnteredUserNameString = userEnteredUserNameString.toUpperCase();
this.userEnteredUserNameString = userEnteredUserNameString;
}
public String getUserEnteredPasswordString() {
return userEnteredPasswordString;
}
public void setUserEnteredPasswordString(String userEnteredPasswordString) {
if (userEnteredPasswordString!=null) userEnteredPasswordString = userEnteredPasswordString.toUpperCase();
this.userEnteredPasswordString = userEnteredPasswordString;
}
In my controller, I have the following code:
FtpScanEvents f = new FtpScanEvents();
if(location.getUserEnteredHostNameString()!=null){
f.setHostName(location.getUserEnteredHostNameString());
}
if(location.getUserEnteredDirectoryString()!=null){
f.setDirectory(location.getUserEnteredDirectoryString());
}
if(location.getUserEnteredUserNameString()!=null){
f.setUserName(location.getUserEnteredUserNameString());
}
if(location.getUserEnteredPasswordString()!=null){
f.setPassword(location.getUserEnteredPasswordString());
}
ftpDao.save(f);
FtpScanEvents table has hostName, directory, username, password, locationId, idx, Id as columns..
hbm mapping file for ftpscanevents:
<hibernate-mapping package="ca.ups.tundra.model">
<class name="FtpScanEvents" table="FTP_SCAN_EVENTS">
<id name="id" type="long">
<generator class="native"/>
</id>
<property name="hostName" type="string" column="HOSTNAME" length="200"/>
<property name="directory" type="string" column="DIRECTORY" length="200"/>
<property name="userName" type="string" column="USERNAME" length="20"/>
<property name="password" type="string" column="PASSWORD" length="20"/>
<many-to-one name="location" class="Location" cascade="all">
<column name="ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
save(e entity) code..
#Override
#Transactional(propagation = Propagation.MANDATORY)
public void save(E entity) {
if(entity == null)
throw new NullArgumentException("entity");
Session s = sessionFactory.getCurrentSession();
s.saveOrUpdate(entity);
}
when it comes to ftpDao.save(f); program terminates and there are no errors in the console..any suggestion is greatly appreciated..
In the save method, I was missing a property. Added that property with a if condition and it worked!

DataServieException: Oracle, EFOracleProvider, POCO and EF 4.0

I try to use the new POCO capabilities of EF 4.0 in combination with the EFOracleProvider. I have recompiled the EFOracleProvider (using ODAC instead of System.Data.OracleClient) to target the .NET Framework 4 (und put it in the 4.0 GAC). Everything ok so far.
I host the Entity Model in a WCF Data Service:
class DivaDispoDataService : DataService<DivaDispoContainer>
{
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
}
My EDMX File looks like this:
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="DivaDispo.Store" Alias="Self" Provider="EFOracleProvider" ProviderManifestToken="10g">
<EntityContainer Name="DivaDispoStoreContainer">
<EntitySet Name="DIW_USER" EntityType="DivaDispo.Store.DIW_USER" store:Type="Tables" Schema="" />
</EntityContainer>
<EntityType Name="DIW_USER">
<Key>
<PropertyRef Name="IDX" />
</Key>
<Property Name="IDX" Type="number" Nullable="false" Precision="10" />
<Property Name="USERNAME" Type="number" Precision="10" />
<Property Name="PERSONNELNUMBER" Type="number" Precision="10" />
<Property Name="PASSWORD" Type="varchar2" MaxLength="10" />
<Property Name="ACTIVATED" Type="number" Precision="1" />
<Property Name="ROLE" Type="number" Precision="1" />
</EntityType>
</Schema>
</edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2008/09/edm" xmlns:cg="http://schemas.microsoft.com/ado/2006/04/codegeneration" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" Namespace="DivaDispo.Model" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
<EntityContainer Name="DivaDispoContainer" annotation:LazyLoadingEnabled="false">
<EntitySet Name="User" EntityType="DivaDispo.Model.User" />
</EntityContainer>
<EntityType Name="User">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Name="ID" Type="Decimal" Nullable="false" Precision="10" Scale="0" />
<Property Name="Username" Type="Decimal" Precision="10" Scale="0" />
<Property Name="PersonnelNumber" Type="Decimal" Precision="10" Scale="0" />
<Property Name="Password" Type="String" MaxLength="10" Unicode="false" FixedLength="false" />
<Property Name="Activated" Type="Boolean" />
<Property Name="Role" Type="Boolean" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs" Space="C-S">
<EntityContainerMapping StorageEntityContainer="DivaDispoStoreContainer" CdmEntityContainer="DivaDispoContainer">
<EntitySetMapping Name="User">
<EntityTypeMapping TypeName="IsTypeOf(DivaDispo.Model.User)">
<MappingFragment StoreEntitySet="DIW_USER">
<ScalarProperty Name="ID" ColumnName="IDX" />
<ScalarProperty Name="Username" ColumnName="USERNAME" />
<ScalarProperty Name="PersonnelNumber" ColumnName="PERSONNELNUMBER" />
<ScalarProperty Name="Password" ColumnName="PASSWORD" />
<ScalarProperty Name="Activated" ColumnName="ACTIVATED" />
<ScalarProperty Name="Role" ColumnName="ROLE" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</EntityContainerMapping>
</Mapping>
</edmx:Mappings>
</edmx:Runtime>
</edmx:Edmx>
My POCO Class looks like this:
public partial class User
{
public virtual decimal ID { get; set; }
public virtual Nullable<decimal> Username { get; set; }
public virtual Nullable<decimal> PersonnelNumber { get; set; }
public virtual string Password { get; set; }
public virtual Nullable<bool> Activated { get; set; }
public virtual Nullable<bool> Role { get; set; }
}
and the DataContext like this:
public partial class DivaDispoContainer : ObjectContext
{
public const string ConnectionString = "name=DivaDispoContainer";
public const string ContainerName = "DivaDispoContainer";
#region Constructors
public DivaDispoContainer()
: base(ConnectionString, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
}
public DivaDispoContainer(string connectionString)
: base(connectionString, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
}
public DivaDispoContainer(EntityConnection connection)
: base(connection, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = false;
}
#endregion
#region ObjectSet Properties
public ObjectSet<User> User
{
get { return _user ?? (_user = CreateObjectSet<User>("User")); }
}
private ObjectSet<User> _user;
}
The POCO classes and the DataContext are generated with the POCO Template from Visual Studio 2010.
When I start my WCF Service and want to query the users I receive an System.Data.Services.DataServiceException which says somtihng like
500: Internal Server error. The type 'System.Data.Entity.DynamicProxies.User_057822846B2B8DD7BB03058490B27D19E6C634EACF33438FE886 19C8BBB1CF74' is not a komplex type or entity type.
When I look in the dubgger I can see that the values have been read from the database (therefore I think the EFOracleProvider works ok) and that the DynamicProxies.User_.... is derrived from my User class (which contains at that point the data from the database). So the question is: Why do I receive this exception? Does anyone know whats going on there? What's the DynamicProxies.User_.... automaic generated class for? The Exception is thrown in the Method GetNonPrimitiveResourceType of the class WebUtil. Or maybe I have something overlooked?
Any help greatly appreciated....
The link from Craig to the blog post http://msdn.microsoft.com/en-us/library/ee705457.aspx revealed the answer. It states there that
The POCO proxy type cannot be directly serialized or deserialized by WCF
and that is exactly my problem. If I remove the virtual from the properties of the genrated POCO class the runtime doesnt generate the proxy types and the exception dissapears.
Thanks again for the link, Craig.

Resources