WCF IClientMessageInspector crash on serialization - wcf

I use the IClientMessageInspector and it's method BeforeSendRequest, to inspect the request messages. The thing is that some of request messages has members, which members are of type object (in the real scenario thre may be in example string or some other value, which is specified in the KnownType attribute):
[DataContract(Namespace = "")]
[KnownType(typeof(SomeValueDTO))]
public class CenDTO
{
[DataMember]
public string Uri { get; set; }
[DataMember]
public object Value { get; set; }
}
Notice, that in this project the namespaces are not defined anywhere. So on the "BeforeSendRequest" I got exception. And looks like this interface uses not the same DataContractSerializer as in the real service, which hasn't such serialization errors or smth like that.
The error:
The empty string '' is not a valid name.
at System.Xml.XmlTextWriter.LookupPrefix(String ns)
at System.Xml.XmlDictionaryWriter.XmlWrappedWriter.LookupPrefix(String namespaceUri)
at System.Xml.XmlDictionaryWriter.XmlWrappedWriter.WriteXmlnsAttribute(String prefix, String namespaceUri)
at System.Xml.XmlDictionaryWriter.WriteXmlnsAttribute(String prefix, XmlDictionaryString namespaceUri)
at System.Runtime.Serialization.XmlWriterDelegator.WriteXmlnsAttribute(XmlDictionaryString ns)
at System.Runtime.Serialization.XmlWriterDelegator.WriteAttributeQualifiedName(String attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
at WriteCenDTOToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, Object[] parameters)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BodyWriterMessage.OnBodyToString(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.ToString(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.ToString()
at CID.TopicAnalyst.CIA.Test.Utils.MessageInspector.BeforeSendRequest(Message& request, IClientChannel channel) in D:\git\...\MessageInspector.cs:line 25
at System.ServiceModel.Dispatcher.ImmutableClientRuntime.BeforeSendRequest(ProxyRpc& rpc)
Implementation of "BeforeSendRequest"(The crash is on the .ToString() ):
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
if(request.Headers.Count > 0)
{
request.Headers.RemoveAt(0);
}
MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
var message = buffer.CreateMessage().ToString();
var resultFile = ConfigurationManager.AppSettings.GetValues("requestFile").First();
_serializer.Write(resultFile, message);
return null;
}
The testing itself is a separate solution, which uses the service's reference.
On the service imnplmentation the operation looks like this:
[ServiceContract]
public interface ISoapService
{
[OperationContract]
SomeListResponseMessage GetSomeList(SomeListRequestMessage request);
}
[MessageContract]
public class SomeListRequestMessage : BaseRequestMessage
{
...
[MessageBodyMember]
public CenDTO Cen { get; set; }
...
}
[DataContract(Namespace = "")]
[KnownType(typeof(SemValueDTO))]
public class CenDTO
{
...
[DataMember]
public object Value { get; set; }
}
Some code of the Testing Solution:
static class Program
{
static void Main(string[] args)
{
while(true)
{
var client = new SoapServiceClient("BasicHttpBinding_ISoapService");
client.Endpoint.Behaviors.Add(new InspectorBehavior());
var soapService = client.ChannelFactory.CreateChannel();
var co = new CooRequestCreator(soapService);
co.CreateAndWriteRequests();
Console.WriteLine("Press y to repeat");
var str = Console.ReadLine();
if(str != "y") break;
}
}
Constructing the request message before calling the service:
class CooRequestCreator : BaseRequestCreator<SomeListRequestMessage>
{
SemValueDTO _semaValue = new SemValueDTO
{
Key = "fb",
Label = "Guild",
Type = "org"
};
public CooRequestCreator(ISoapService soapService) : base(soapService)
{
}
protected override SomeListRequestMessage CreateMinRequest()
{
return new SomeListRequestMessage
{
Cen =
new CenDTO
{
Value = _semaValue,
},
MaxCount = 5
};
}
Maybe someone can has the same experience and can help with that?

Related

WCF Cannot deserialize when using IDataContractSurrogate

I'm using WCF service with WebHttpBinding. I have written custom IDataContractSurrogate implementation to serialize enum as strings.
Enums are serialization WORKS, but deserialization fails.
when request contains enum, then I get:
The remote server returned an unexpected response: (400) Bad Request.
or when response contains an enum, then I get:
InvalidCastException: Specified cast is not valid
Server stack trace:
at ReadMyResponseFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
at ...
the server code:
string baseAddress = "http://localhost:8733/Design_Time_Addresses/FingerprintService/";
_serviceHost = new WebServiceHost(myServiceInstance, new Uri(baseAddress));
_serviceHost.AddServiceEndpoint(typeof (IMyService), new WebHttpBinding(WebHttpSecurityMode.None), baseAddress);
EndpointExtension.Setup(_serviceHost.Description.Endpoints[0]);
_serviceHost.Open();
client code:
IMyService FingerprintService()
{
var channelFaftory = new WebChannelFactory<IMyService>(new Uri(TbxUri.Text));
EndpointExtension.Setup(channelFaftory.Endpoint);
return channelFaftory.CreateChannel();
}
the endpoint setup (common for both host and client):
public static void Setup(ServiceEndpoint endpoint)
{
var webHttpBehavior = endpoint.Behaviors.Find<WebHttpBehavior>();
if (webHttpBehavior == null)
{
webHttpBehavior = new WebHttpBehavior();
endpoint.Behaviors.Add(webHttpBehavior);
}
foreach (OperationDescription opertion in endpoint.Contract.Operations)
{
var dataContractBehavior = opertion.Behaviors.Find<DataContractSerializerOperationBehavior>();
dataContractBehavior.DataContractSurrogate = new EnumSurrogate();
}
}
}
and finaly, the surrogate:
public class EnumSurrogate : IDataContractSurrogate
{
public Type GetDataContractType(Type type)
{
if (type.IsEnum)
{
return typeof(string);
}
return type;
}
public object GetObjectToSerialize(object obj, Type targetType)
{
if (obj is Enum)
{
return obj.ToString();
}
return obj;
}
public object GetDeserializedObject(object obj, Type targetType)
{
if (obj is string && targetType.IsEnum)
{
return Enum.Parse(targetType, (string)obj);
}
return obj;
}
//other methods throws NotImplementedException
}
your approach works nicely when serializing, but will not work when deserializing. This will fail because primitive values cannot be surrogated while deserializing.
https://canbilgin.wordpress.com/2012/06/07/how-to-serialize-an-enum-as-string-with-idatacontractsurrogate/

OData $select fails with missing property error

I'm building an odata service that is used for reading from sql and then rendering the results in json format. I'm not using entityframework though.
When applying the $select filter, if I have less properties than my model (removing a nullable one), I'm getting the following error. If I have the exact same amount of properties, everything works fine.
{
"error": {
"code": "",
"message": "An error has occurred.",
"innererror": {
"message": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.",
"type": "System.InvalidOperationException",
"stacktrace": "",
"internalexception": {
"message": "The EDM instance of type '[PrototypeOData.Models.DefaultRule Nullable=True]' is missing the property 'DateLastModified'.",
"type": "System.InvalidOperationException",
"stacktrace": " at System.Web.OData.EntityInstanceContext.GetPropertyValue(String propertyName)\r\n at System.Web.OData.Formatter.Serialization.ODataEntityTypeSerializer.CreateStructuralProperty(IEdmStructuralProperty structuralProperty, EntityInstanceContext entityInstanceContext)\r\n at System.Web.OData.Formatter.Serialization.ODataEntityTypeSerializer.CreateStructuralPropertyBag(IEnumerable`1 structuralProperties, EntityInstanceContext entityInstanceContext)\r\n at System.Web.OData.Formatter.Serialization.ODataEntityTypeSerializer.CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)\r\n at System.Web.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteEntry(Object graph, ODataWriter writer, ODataSerializerContext writeContext)\r\n at System.Web.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)\r\n at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, IEdmTypeReference feedType, ODataWriter writer, ODataSerializerContext writeContext)\r\n at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteObjectInline(Object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)\r\n at System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteObject(Object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content, HttpContentHeaders contentHeaders)\r\n at System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__14.MoveNext()"
}
}
}
}
My model looks like this:
public class DefaultRule
{
public string Id { get; set; }
public int? RequestedCount { get; set; }
public DateTime? DateLastModified { get; set; }
}
In my controller the calls are as follows:
public IHttpActionResult Get(ODataQueryOptions<DefaultRule> options)
{
.............
var res = options.SelectExpand.ApplyTo(result, new ODataQuerySettings() { PageSize = 100}).AsQueryable();
//return result;
return Ok(res, res.GetType());
}
private IHttpActionResult Ok(object content, Type type)
{
Type resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
}
Is there any way I can mark specific properties as optional?
Any thoughts are appreciated.
This is because your the result of $select is not your original model. Then error occurs in Serialization. Try add the pagesize in attribute like:
[EnableQuery(PageSize=100)]
or create your own attribute
public class MyEnableQueryAttribute : EnableQueryAttribute
{
public override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)
{
return options.SelectExpand.ApplyTo(result, new ODataQuerySettings() { PageSize = 100}).AsQueryable().
}
}
[MyEnableQueryAttribute]
public IHttpActionResult Get()
{
....
return result;
}

Cannot consume WCF Rest Services in WCF Client

I have a Service and the releated interface under namespace called "WCFService":
[ServiceContract]
public interface IBook
{
[OperationContract]
[WebInvoke(Method="GET"
,ResponseFormat=WebMessageFormat.Json
,BodyStyle=WebMessageBodyStyle.Wrapped
,UriTemplate="/?bookID={bookID}")]
Book Get(int bookID);
}
//========================================================
public Book Get(int bookID)
{
return bookList.Where(p => p.BookID == bookID).FirstOrDefault();
}
And the Book DataModel is under another namespace called "WCFModel":
[DataContract]
public class Book
{
[DataMember]
public int BookID { get; set; }
[DataMember]
public string BookName { get; set; }
[DataMember]
public decimal BookPrice { get; set; }
[DataMember]
public string BookPublish { get; set; }
}
After set the config file, I got the service run ok.
Then I planned to consume it in client side. I added a windows form application to the project and added reference to the WCFModel book datamodel, I used below code to extract the data:
string serviceURL = "http://localhost:15020/BookService.svc/?bookID=" + txtBookID.Text.Trim();
var request = WebRequest.Create(serviceURL);
var response = request.GetResponse();
DataContractSerializer serializer = new DataContractSerializer(typeof(WCFModel.Book));
var bookObj = serializer.ReadObject(response.GetResponseStream());
But the result was, VS thrown me an exception at the ReadObject below:
Error when deserializing the WCFModel.Book type, Data at the root level is invalid.
stack trace below:
在 System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
在 System.Xml.XmlUTF8TextReader.Read()
在 System.Xml.XmlBaseReader.IsStartElement()
在 System.Xml.XmlBaseReader.IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
在 System.Runtime.Serialization.XmlReaderDelegator.IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
在 System.Runtime.Serialization.XmlObjectSerializer.IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns)
在 System.Runtime.Serialization.DataContractSerializer.InternalIsStartObject(XmlReaderDelegator reader)
在 System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
在 System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
I don't know why, After searching a lot, I still can't get the point. Anyone can give me some reference? thx.
I hope this may work for you!
Try implementing this!
WebClient proxy = new WebClient();
string serviceURL =
string.Format("http://localhost:15020/BookService.svc/?bookID=" + txtBookID.Text.Trim().ToString());
byte[] data = proxy.DownloadData(serviceURL);
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj =
new DataContractJsonSerializer(typeof(Book));
Book book = obj.ReadObject(stream) as Book;
Console.WriteLine("Book ID : " + book.BookID);
Console.WriteLine("Book Name : " + book.BookName);
Console.WriteLine("Book ID : " + book.BookPrice);
Console.WriteLine("Book ID : " + book.BookPublish);
See this link
EDIT: Change BodyStyle=WebMessageBodyStyle.Wrapped to BodyStyle=WebMessageBodyStyle.Bare.

NHibernate "Invalid Cast (check your mapping for property type mismatches); setter of System.Object"

I've been upgrading my NHibernate installation (was still on 1.2!). All has been good until I tried to setup an Interceptor. If I add an Interceptor to the OpenSession() call, then I get this error when trying to load an entity from the DB:
"Invalid Cast (check your mapping for property type mismatches); setter of System.Object"
If there is no Interceptor, this error does not occur.
The Interceptor is very simple, and in fact I pretty much commented out everything in order to test:
public class Interceptor : EmptyInterceptor
{
public override void AfterTransactionBegin(ITransaction tx)
{
}
public override void AfterTransactionCompletion(ITransaction tx)
{
}
public override void BeforeTransactionCompletion(ITransaction tx)
{
}
//public override int[] FindDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
//{
//}
//public override object GetEntity(string entityName, object id)
//{
//}
//public override string GetEntityName(object entity)
//{
//}
public override object Instantiate(string entityName, EntityMode entityMode, object id)
{
//((EntityBase)entity).Instantiate(entityName, entityMode, id)
return new object();
}
//public override bool? IsTransient(object entity)
//{
//}
public override void OnCollectionRecreate(object collection, object key)
{
}
public override void OnCollectionRemove(object collection, object key)
{
}
public override void OnCollectionUpdate(object collection, object key)
{
}
public override void OnDelete(object entity, object id, object[] state, string[] propertyNames, IType[] types)
{
//((EntityBase)entity).OnDelete(entity, id, state, propertyNames, types);
}
//public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types)
//{
//}
public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types)
{
//if (entity.GetType().FullName.Equals("EntityBase"))
// return ((EntityBase)entity).OnLoad(entity, id, state, propertyNames, types);
//else
return false;
}
//public override NHibernate.SqlCommand.SqlString OnPrepareStatement(NHibernate.SqlCommand.SqlString sql)
//{
//}
public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
{
//return ((EntityBase)entity).OnSave(entity, id, state, propertyNames, types);
return true;
}
public override void PostFlush(System.Collections.ICollection entities)
{
}
public override void PreFlush(System.Collections.ICollection entities)
{
}
public override void SetSession(ISession session)
{
}
}
As such I'm totally baffled. Like I said, with the Interceptor it errors on loading and hydrating entities (after the OnLoad event fires), without the Interceptor it's fine. I'm using nHibernate 3.2.0.2001 with .Net4 against SQL Server 2008.
Any help appreciated! Ben
Unfortunately I've been unable to progress this issue, I had to switch to Linq-SQL because of this specific problem, and that I couldn't find a solution in the timeframe required to use these templates. Therefore I can't provide any more information at this time.

Mapped Objectified relationship with nhibernate can not initialize collection

I'm mapping a objectified relationship (the many->many mapping table contains properties),
following this guide.
The SQL generated(see exception) is working and returns what i want(strictly speaking it should have been an inner join?).
But I get a GenericADOException saying:
could not initialize a collection: [Questionnaires.Core.Questionnaire.Questions#CBDEDAFC183B4CD7AF1422423A91F589][SQL: SELECT questions0_.ida_questionnaire_id as ida4_2_, questions0_.ida_questionnaire_question_id as ida1_2_, questions0_.ida_questionnaire_question_id as ida1_5_1_, questions0_.question_no as question2_5_1_, questions0_.ida_question_id as ida3_5_1_, questions0_.ida_questionnaire_id as ida4_5_1_, question1_.ida_question_id as ida1_3_0_, question1_.ida_question_type_id as ida2_3_0_, question1_.description as descript3_3_0_, question1_.validate_max as validate4_3_0_, question1_.validate_min as validate5_3_0_ FROM ida_questionnaire_question questions0_ left outer join ida_question question1_ on questions0_.ida_question_id=question1_.ida_question_id WHERE questions0_.ida_questionnaire_id=?]
I'm guessing this is because Questionnaire is really mapping to QuestionnaireQuestion not Question(Questionnaire->hasMany->QuestionnaireQuestion<-hasMany<-Question). But I can't seem to find a way of going around this.
Question:
public class Question : PersistentObjectWithTypedId<string>
{
#region Constructors
public Question()
{
Alternatives = new List<Alternative>();
Questionnaires = new List<Questionnaire>();
}
public Question(string description)
: this()
{
Check.Require(!string.IsNullOrEmpty(description) && description.Trim() != string.Empty);
Description = description;
}
#endregion
#region Properties
public virtual string Type { get; set; }
public virtual string Description { get; set; }
public virtual int Order { get; set; }
public virtual IList<Questionnaire> Questionnaires { get; set; }
public virtual IList<Alternative> Alternatives { get; set; }
public virtual Validator MyValidator { get; set; }
}
public class QuestionMap : ClassMap<Question>
{
public QuestionMap()
{
WithTable("ida_question");
Id(x => x.ID, "ida_question_id").WithUnsavedValue(0).GeneratedBy.UuidHex("");
Map(x => x.Description, "description").AsReadOnly();
Map(x => x.Type, "ida_question_type_id").AsReadOnly();
Component<Core.Validator>(x => x.MyValidator, m =>
{
m.Map(x => x.Type, "ida_question_type_id");
m.Map(x => x.RangeMin, "validate_min");
m.Map(x => x.RangeMax, "validate_max");
});
HasMany<QuestionnaireQuestion>(x => x.Questionnaires)
.Cascade.AllDeleteOrphan()
.WithKeyColumn("ida_question_id");
HasMany<Alternative>(x => x.Alternatives)
.IsInverse()
.WithKeyColumn("ida_question_id")
.AsBag().SetAttribute("cascade", "all");
}
}
QuestionnaireQuestion:
public class QuestionnaireQuestion : PersistentObjectWithTypedId<string>
{
protected QuestionnaireQuestion()
{
}
public virtual int QuestionOrder { get; set; }
public virtual Question Question {get;set;}
public virtual Questionnaire Questionnaire { get; set; }
}
public class QuestionnaireQuestionMap : ClassMap<QuestionnaireQuestion>
{
public QuestionnaireQuestionMap()
{
WithTable("ida_questionnaire_question");
SetAttribute("lazy", "false");
Id(x => x.ID, "ida_questionnaire_question_id")
.WithUnsavedValue(0)
.GeneratedBy.UuidHex("");
References(x => x.Question, "ida_question_id")
.WithForeignKey("ida_question_id")
.FetchType.Join();
References(x => x.Questionnaire, "ida_questionnaire_id")
.WithForeignKey("ida_questionnaire_id")
.FetchType.Join();
Map(x => x.QuestionOrder, "question_no");
}
}
Questionnaire:
public class Questionnaire : PersistentObjectWithTypedId<string>
{
#region Constructors
public Questionnaire()
{
Questions = new List<Question>();
}
public Questionnaire(string description) : this()
{
Check.Require(!string.IsNullOrEmpty(description) && description.Trim() != string.Empty);
Description = description;
}
#endregion
#region Properties
public virtual string Description { get; set; }
public virtual IList<Question> Questions { get; set; }
#endregion
}
public class QuestionnaireMap : ClassMap<Questionnaire>
{
public QuestionnaireMap(){
WithTable("ida_questionnaire");
SetAttribute("lazy", "false");
Id(x => x.ID, "ida_questionnaire_id")
.WithUnsavedValue(0)
.GeneratedBy.UuidHex("");
Map(x => x.Description);
HasMany<QuestionnaireQuestion>(x => x.Questions)
.Cascade.AllDeleteOrphan()
.WithKeyColumn("ida_questionnaire_id");
}
}
The result of running the SQL in the exception in the DB is 6 rows (the expected number) containing:
IDA4_2_: Guids
IDA1_2_: Guids
IDA1_5_1_: Guids
QUESTION2_5_1: Number (order
property)
IDA3_5_1_: Guids
IDA4_5_1: Guids
IDA1_3_0_: Guids
IDA2_3_0_: MOBILEPHONE (type
property)
DESCRIPT3_3_0_: mobiltelefon
(Description property)
VALIDATE4_3_0_: (RangeMin property)
VALIDATE5_3_0_: (RangeMax property)
The complete exception is:
[InvalidCastException: Cant use object type Questionnaires.Core.QuestionnaireQuestion as Questionnaires.Core.Question.]
NHibernate.Collection.Generic.PersistentGenericBag`1.ReadFrom(IDataReader reader, ICollectionPersister persister, ICollectionAliases descriptor, Object owner) +160
NHibernate.Loader.Loader.ReadCollectionElement(Object optionalOwner, Object optionalKey, ICollectionPersister persister, ICollectionAliases descriptor, IDataReader rs, ISessionImplementor session) +407
NHibernate.Loader.Loader.ReadCollectionElements(Object[] row, IDataReader resultSet, ISessionImplementor session) +412
NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +472
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1010
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +114
NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type) +362
[GenericADOException: could not initialize a collection: [Questionnaires.Core.Questionnaire.Questions#CBDEDAFC183B4CD7AF1422423A91F589][SQL: SELECT questions0_.ida_questionnaire_id as ida4_2_, questions0_.ida_questionnaire_question_id as ida1_2_, questions0_.ida_questionnaire_question_id as ida1_5_1_, questions0_.question_no as question2_5_1_, questions0_.ida_question_id as ida3_5_1_, questions0_.ida_questionnaire_id as ida4_5_1_, question1_.ida_question_id as ida1_3_0_, question1_.ida_question_type_id as ida2_3_0_, question1_.description as descript3_3_0_, question1_.validate_max as validate4_3_0_, question1_.validate_min as validate5_3_0_ FROM ida_questionnaire_question questions0_ left outer join ida_question question1_ on questions0_.ida_question_id=question1_.ida_question_id WHERE questions0_.ida_questionnaire_id=?]]
NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type) +528
NHibernate.Loader.Collection.CollectionLoader.Initialize(Object id, ISessionImplementor session) +74
NHibernate.Persister.Collection.AbstractCollectionPersister.Initialize(Object key, ISessionImplementor session) +59
NHibernate.Event.Default.DefaultInitializeCollectionEventListener.OnInitializeCollection(InitializeCollectionEvent event) +573
NHibernate.Impl.SessionImpl.InitializeCollection(IPersistentCollection collection, Boolean writing) +150
NHibernate.Collection.AbstractPersistentCollection.ForceInitialization() +287
NHibernate.Engine.StatefulPersistenceContext.InitializeNonLazyCollections() +213
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +171
NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister) +493
NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) +82
NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) +54
NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) +206
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +133
NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +948
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +436
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +236
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +1303
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +125
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +145
NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) +66
NHibernate.Impl.SessionImpl.Get(Object id) +91
SharpArch.Data.NHibernate.RepositoryWithTypedId`2.Get(IdT id) +152
Questionnaires.Controllers.QuestionnaireController.Create(String username, String id) in C:\Documents and Settings\berbor\Mine dokumenter\Visual Studio 2008\Projects\Questionnaires\Questionnaires.Controllers\QuestionnaireController.cs:40
lambda_method(ExecutionScope , ControllerBase , Object[] ) +205
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.b__7() +52
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +254
System.Web.Mvc.<>c__DisplayClassc.b__9() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +350
System.Web.Mvc.Controller.ExecuteCore() +110
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +119
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +41
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
As for the reason I'm doing this:
One Questionnaire may have many Questions, One Question may have many Questionnaire.
I want to be able to give Questions some properties dependent on context (which Questionnaire is in), one question may be required in one questionnaire but not another etc. It's more than just order, that was just an example trying to keep it simple.
The exception is when trying to load data into Questionnaire.IList<Question>. And it's still thrown after I modify my IList<Questionnaire> to IList<QuestionnaireQuestion> and the respective mappings.
The problem then would be that Questionnaire.Questions is mapped as containing QuestionnaireQuestion but is of type Question. But if I try to map it as containing QuestionnaireQuestion my SQL does no join at all and it still fails.
Is this what I should do, just that I'm doing it wrong?
In the example I read he does it like I did as far as I can see, only difference is the newer version of FluentNhibernate that now uses Generics. So I need to specify the correct type.
Then, you should not have a List of Questionnaires in your Question class, but a List of QuestionnaireQuestion objects.
Are you sure you receive an ADO.NET Exception ?
Can you execute the generated query against your database ?
I don't understand your situation however, what is this QuestionairreQuestion class ? You're not using it in your Question class ?
I understand that you want to have an order in which your questions should occur.
So, if you have extra properties , I think you should use the QuestionairreQuestion class in your Question class.
But, if you only have this QuestionairreQuestion class in order to enforce an 'order' (and no other attributes), then, you could maybe use another Collection-Type instead of an IList.
There are collections in NHibernate which allow you to have ordered-collections (a map , for instance). So, you could use this collection in your Question class to hold Questionairre objects.
(ps: nhibernate generates an outer join, because you didn't specify in your mapping that the collection should not be null. So, an outer join is used because in some circumstances, it could be possible that you have a Question without Questionaires, as far as nhibernate is concerned).