Error trying to implement Code First (CTP 5) in WCF Data Service - wcf

I am trying to implement Code First (CTP 5) in my WCF Data Service (OData). Its a simple scenario, but I get a HTTP 500 Internal Server Error with no much details. I put this on Data Service to show fault error details.
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
However I still don't see what is going wrong.
In Constructor of my DbContext implementation I am calling base class with Connection string like below.
public MyContext() : base("MyConnection")
{
}
And I have a simple member in it like this.
public DbSet<MyData> MyData{ get; set; }
I implemented the members of MyData class as needed.
All I get in browser is 500 Internal server error without any further details.
What could wrong with my implementation?

After some research, trial and error I found the issue. Putting it here to help others landing in this situation. One of the objects in my Model is being treated as a Complex Type and I am referring to it in another POCO object in my Model as a Collection, which apparently is not supported by EF Code First (which makes sense). This links helped me understand it better.
[Complex Types]
http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx
[Conventions in CodeFirst]http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-code-first.aspx
Please be aware that there could be many such instances of 500 which is causd due to improper modellign of Objects. Make sure to verify the Conventions and how Code First works in background to understand thee relationships.

Related

Using DLL references of WCF service in another WCF service

Sorry for the long question in the first place. I would rather prefer to come up with a shorter question but this is the most stripped version I could provide that I can clearly explain my point.
I have been trying to deliver a wrapper service to our client which should provide multiple services in it. Idea behind it is to reduce multiple calls to a one call and return a single object which has other associated objects in it. To illustrate my point, let me give following example:
Let's say we have following services:
MyCompany.Services.Donation
MyCompany.Services.Payment
MyCompany.Services.PartialPayment
Normally client should query Donation service (with a donationID) to get donation information, and then using the retrieved donation information, they should query Payment service to get payment related details, and if the payment is done in multiple small payments, using retrieved payment information, they should query PartialPayment service to get all donation information for a particular Donor.
Instead of client doing this, I am going to provide a wrapper service to accept donationID as a single parameter and return a class similar to this:
[DataContract(Namespace = "http://MyCompany.Services.DonationDetail")]
public class DonationDetail
{
[DataMember]
public MyCompany.Services.Donation.Record donationRecord;
[DataMember]
public PaymentDetail paymentDetail;
}
[DataContract(Namespace = "http://MyCompany.Services.DonationDetail")]
public class PaymentDetail
{
[DataMember]
public MyCompany.Services.Payment.Record paymentRecord;
[DataMember]
public List<MyCompany.Services.PartialPayment.Record> partialPayments;
}
So an instance of DonationDetail record should return all relevant information with that donation.
My problem arises when I use these individual services DLL's* in my wrapper service since any class I pass to client using wrapper service becomes part of the wrapper service and client can't use them right away with the corresponding types they retrieved using service references without writing a custom construction method to convert one type to another - although they are same objects. Instead of referring classes in original namespace, service uses following classes something like that now for the classes mentioned above:
DonationDetail.Record (Donation Record - I would expect MyCompany.Services.Donation.Record)
DonationDetail.Record1 (Payment Record - I would expect MyCompany.Services.Payment .Record)
DonationDetail.Record2 (PartialPayment Record - I would expect MyCompany.Services.PartialPayment.Record)
Is there a way to provide such an interface without a custom constructor? So, if they use "PartialPayment" namespace for the MyCompany.Services.PartialPayment WCF service, can they do something below after DonationDetail is retrieved via wrapper service?
PartialPayment.Record partialPayment = dDetailObj.paymentDetail.partialPayments[0];
*: Don't ask me why I don't use service references unless that is the cause of the problem, since that option gives me other problems to me at this point)
So I think what you are saying, effectively, is that if you have two different services that return the same object and when you add this as two different service references to the client, even though ultimately they are the same object as far as the services are concerned (since they reference the same DLL), the client sees them as two different types so you can't take the object returned from one and send it as the input to the other service.
Assuming I have understood your question (and I apologise if I have not)...
You could map one type to the other by constructing it and setting the properties but that is really kind of a pain and not very friendly to the consumer etc, hence I am going to suggest something kind of radical...
Ditch the service references on the client.
Yup, I said it, why would I suggest such a thing!?! Here's why...
First of all I would make sure my project was structured something like this:
Donation Detail Client Library
IDonationService (this is the service contract - notice no implementation in the client library)
DonationRecord
Payment Detail Client Library
IPaymentService (this is the service contract - notice no implementation in the client library)
PaymentRecord
Partial Payment Client Library
IPartialPaymentService (this is the service contract - notice no implementation in the client library)
PartialPaymentRecord
Wrapper Service Client Library (which references the three other client libraries)
IWrapperService (this is the service contract - notice no implementation in the client library)
Incidentally, I gave your records different class names but you could use namespaces if you like and call them all Record (I think calling them different names is less confusing, but that is probably just me).
On the service end you reference the client library that you need to implement the service and do whatever you have to do just as you always have.
On the client you reference the client libary (or libraries depending on what service you want to call) too, in the same way (so you effectively have a shared library between server and client - yeah old skool, but hey, you will see why).
The client then has the interface for the service contract and all the data contracts so it does not need the whole service reference, generated code thing. Instead what you can do on your client is something like this:
DonationRecord donation;
using (var cf = new ChannelFactory<IDonationService>("EndpointNameInConfigurationFile"))
{
IDonationService donationservice = cf.CreateChannel();
donation = donationservice.GetDonation("Donation1234");
}
using (var cf = new ChannelFactory<IWrapperService>("EndpointNameInConfigurationFile"))
{
IWrapperService wrapperService = cf.CreateChannel();
wrapperService.DoSomethingWithDonation(donation);
}
There, you see I took the data contract from one service and sent it to a completely unrelated service and it looks natural (I have an object that is returned from a method on class X and I took it and passed it as an agrument on class Y, job done, just like programming).
NOTE: Using this technique will not stop service references from working just as they always have so any existing client code would not have to change, just if you use your new wrapper service, you could use it like this to save having to map types.

Problem with WCF/EF 4.1 Lazy Loading

I'm getting data for my application through WCF service. And on the server side the service is using EF4.1 as a data access.
Service method looks kind of like this :
public List<JobOffer> GetAllJobOffers()
{
var allJobOffers = _jobOffersRepository.GetAll().ToList();
return allJobOffers;
}
And the repository is done this way
public override IQueryable<JobOffer>GetAll()
{
return _context.JobOffers.Include(c => c.Company);
}
I am getting this strange error :
An error occurred while receiving the HTTP response to http://localhost:8080/JobsService/ws. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
In debug mode after hitting F5 it starts to loop forever.
In my case it should some problem with lazy loading on the server side. Because when I am calling the service to return objects with simple structure it works like a champ. What could be messed up? And what is the best practice to eager load objects with EF ?
When using EF over WCF lazy loading should be turned off because serialization will trigger lazy loading of every navigation property. Another problem are cyclic references which are not serializable by default. If your Company has also navigation property to its Jobs it makes cyclic reference.
I think your problem is more like to be related to the cyclic relationship. this all happens when serialization comes in scope. lets say u have e entity person which has property addresses which is marked as lazy. on the other side of relationship Addresses entity has a navigation property for Person entity. as serialization takes place it goes through each property of the person entity and as it access Addresses navigation property starts to load it. now it starts to serialize Address entity and as it access Person navigation property it goes back to that property and starts to serialize it and it creates situation when cyclic serialization starts and can not be completed. to overcome this problem u do not have to turn of lazy loading but all u have to do is to decorate you datacontract in (in this case Person and Addresse) with [DataContract(IsReference = true)] and everything works like an charm.
I know this is a bit of an old question, but based on your experiences in your question, I think it might help if you take a look through one of my recent posts
http://sanderstechnology.com/2013/more-with-the-entity-framework-v6-rc1/12423/
I walk through how to send a semi-complex EF object graph which is deserialized through WCF, and I handle lazy loading, proxy generation and cyclic reference issues. It might be worth a look.

Request/Response pattern in SOA implementation

In some enterprise-like project (.NET, WCF) i saw that all service contracts accept a single Request parameter and always return Response:
[DataContract]
public class CustomerRequest : RequestBase {
[DataMember]
public long Id { get; set; }
}
[DataContract]
public class CustomerResponse : ResponseBase {
[DataMember]
public CustomerInfo Customer { get; set; }
}
where RequestBase/ResponseBase contain common stuff like ErrorCode, Context, etc. Bodies of both service methods and proxies are wrapped in try/catch, so the only way to check for errors is looking at ResponseBase.ErrorCode (which is enumeration).
I want to know how this technique is called and why it's better compared to passing what's needed as method parameters and using standard WCF context passing/faults mechanisms?
The pattern you are talking about is based on Contract First development. It is, however not necessary that you use the Error block pattern in WCF, you can still throw faultexceptions back to the client, instead of using the Error Xml block. The Error block has been used for a very long time and therefore, a lot of people are accustom to its use. Also, other platform developers (java for example) are not as familiar with faultExceptions, even though it is an industry standard.
http://docs.oasis-open.org/wsrf/wsrf-ws_base_faults-1.2-spec-os.pdf
The Request / Response pattern is very valuable in SOA (Service Oriented Architecture), and I would recommend using it rather than creating methods that take in parameters and pass back a value or object. You will see the benefits when you start creating your messages. As stated previously, they evolved from Contract First Development, where one would create the messages first using XSDs and generate your classes based on the XSDs. This process was used in classic web services to ensure all of your datatypes would serialize properly in SOAP. With the advent of WCF, the datacontractserializer is more intelligent and knows how to serialize types that would previously not serialize properly(e.g., ArrayLists, List, and so on).
The benefits of Request-Response Pattern are:
You can inherit all of your request and responses from base objects where you can maintain consistency for common properties (error block for example).
Web Services should by nature require as little documentation as possible. This pattern allows just that. Take for instance a method like public BusScheduleResponse GetBusScheduleByDateRange(BusDateRangeRequest request); The client will know by default what to pass in and what they are getting back, as well, when they build the request, they can see what is required and what is optional. Say this request has properties like Carriers [Flag Enum] (Required), StartDate(Required), EndDate(Required), PriceRange (optional), MinSeatsAvailable(Option), etc... you get the point.
When the user received the response, it can contain a lot more data than just the usual return object. Error block, Tracking information, whatever, use your imagination.
In the BusScheduleResponse Example, This could return Multiple Arrays of bus schedule information for multiple Carriers.
Hope this helps.
One word of caution. Don't get confused and think I am talking about generating your own [MessageContract]s. Your Requests and Responses are DataContracts. I just want to make sure I am not confusing you. No one should create their own MessageContracts in WCF, unless they have a really good reason to do so.

WCF and member-method replacements

I have an object of the form:
public class Report
{
m_filter1;
m_filter2;
...
m_filtern;
AddFilter1(int a)
{
m_filter1 = /* some logic of filtering results using the value of a */
}
...
}
Also, a corresponding static method used to utilize the Report class:
public static List<Result> GetResults(Report r)
{
/* use r to query the DB and return an array of results */
}
As this method needs to be exposed using WCF, i must also make the class Report available for 'outside' (client) use, but its member-methods, which hide the internal plumbings, cannot be used in the WCF proxy class generated for it.
As i can't expose the private members of Report, how can i elegantly solve the problem of member-methods needed on the consuming side?
I thought of a service contract of the form:
public class ReportingService
{
Report m_report = new Report();
AddFilter1(int a)
{
m_report.AddFilter1(a);
}
...
}
i.e., to wrap the member-methods of the Report class using a single Report instance - but that puts a limitation of using a single, non thread-safe object shared by all the calls to the service.
Is there anything basic i'm missing here? i'm quite new to WCF, so i've probably overlooked an easy pattern of solving this out.
Thanks,
Harel
Well, as you've noticed - WCF only ever conveys data across the server-client link - and that's absolutely intentional. WCF handles serialized messages - data only. Think about it for a second: WCF is totally interoperable - your client could be a PHP site calling you - how would those guys be able to execute your .NET code??
So basically the design recommendation is: make sure your data contracts are just that - pure data, no behaviors, no methods, nothing like that.
If you need to do something on a piece of data - define a service method for it! That's what the whole service-oriented architecture is all about.
So basically: there's really no elegant or proper way to achieve what you want - except for making your methods into service methods that operate on simple data contracts.

How to prevent 'Specified' properties being generated in WCF clients?

I have two .NET 3.5 WCF services build with VS2008.
I have two WCF clients in Silverlight to consume these services. The clients are generated with the 'Add Service Reference'. I am using Silverlight 4.
ONE of the proxies is generated with Specified properties for each property. This is a 'message-in' class for my service method :
// properties are generated for each of these fields
private long customerProfileIdField;
private bool customerProfileIdFieldSpecified;
private bool testEnvField;
private bool testEnvFieldSpecified;
Now my other service (still with a Silverlight client) does NOT generate Specified properties.
Now I don't care about 'tenets of good SOA'. I just want to get rid of these damn properties because in the context of what I'm doing I absolutely hate them.
There has to be some difference between the two services - but I don't want to have to completely rip them apart to find out the difference.
A similar question before had the answer 'you cant do it' - which is definitely not true because I have it - I just don't know what I did differently.
Edit: I am now in a situation where I regenerate my Silverlight 4 proxy to my 3.5 WCF service (all on the same localhost machine) that sometimes I get 'Specified' properties and sometimes I don't. I no longer think (as I suspected originally) that this is due solely to some endpoint configuration or service level [attribute]. Theres certain triggers in the message itself that cause Specified to be generated (or not). There may be many factors involved or it may be something very simple.
try this in your WCF service where the property is declared
[DataMember(IsRequired=true)]
public bool testEnvField { get; set; }
IsRequired=true will negate the need for the testEnvFieldSpecified property
These extra Specified properties are generated for value types which are being specified as optional in either the contract or the attribute markup.
As value types have a value by default, the extra Specified flags are being added for these properties, to allow the client (and server) to distinguish between something explicitly not specified or explicitly specified - which may well be set to the default value. Without it, integers would always end up being 0 (and being serialized) even if you don't set them (because of the mapping to int) in your client code. So when you do, you need to also make sure that you set the Specified flag to true, otherwise these properties will not get serialized.
So to prevent these flags being generated for value types, you would have to change the contract to make these value type properties mandatory, instead of optional.
Hope that makes sense.
OK I've found one thing so far that will cause Specified properties to be generated:
The presence of an XTypedElement in the message.
These are used by Linq2XSD. I was returning an element from a Linq2XSD model.
This triggered Specified properties to be generated EVERYTHING in all my classes :
public XTypedElement Foo { get; set; }
This however didn't :
public XElement Foo { get; set; }
Still curious as to why this is, and if there are any other things that trigger this.
NOTE: I realize this is an old question. I'm adding this here because this question comes up as a top result on Google, and it's helpful information for whoever comes looking.
Try adding this line into your operation contract declaration:
[XmlSerializerFormat]
It should look something like this:
namespace WebServiceContract
{
[ServiceContract(Namespace = "http://namespace")]
[XmlSerializerFormat] //This line here will cause it to serialize the "optional" parameters correctly, and not generate the extra
interface InterfaceName
{
/*...Your web service stuff here...*/
}
}
I found that if I put a DataTable in a service DataContract then the generated client will use xml serializer and thus generate the *IsSpecified members.