Alternative for dataset/datatable returned from ajax enabled wcf service? - wcf

I have seen blogs and people saying Returning dataset/datatable from an ajax enabled wcf service is a bad idea.... I have gone through this Scott Hanselman's blog about datasets fr0m wcf...
So what is the alternative for dataset returned form ajax enabled wcf service?

Well, basically, on your server side (where your service method is implemented), either use straight ADO.NET SqlDataReader and assemble the data retrieved into custom classes, or use an ORM like Linq-to-SQL or the Entity Framework or NHibernate or ... or... or..... to do this job.
Then, when you need to return data, either return a List<MyClass> or some other structure, which gets serialized into JSON or XML and doesn't carry the overhead of a whole DataSet/DataTAble.

Related

How to convert a LinqExpression into OData query URI

There are a lot of answers on how to convert ODataQuery into an Expression or into a Lambda, but what I need is quite the opposite, how to get from a Linq Expression the OData query string.
Basically what I want is to transcend the query to another service. For example, having 2 services, where your first service is not persisting anything and your second service is the one that will return the data from a database. Service1 sends the same odata request to Service2 and it can add more parameters to the original odata request to Service2
What I would like:
public IActionResult GetWeatherForecast([FromServices] IWeatherForcastService weatherForcastService)
{
//IQueryable here
var summaries = weatherForcastService.GetSummariesIQ();
var url = OdataMagicHelper.ConvertToUri(summaries);
var data = RestClient2.Get(url);
return data;
}
OP Clarified the request: generate OData query URLs from within the API itself.
Usually, the queries are so specific or simple, that it's not really necessary to try and generate OData urls from within the service, the whole point of the service configuration is to publish how the client could call anything, so it's a little bit redundant or counter-intuitive to return complex resource query URLs from within the service itself.
We can use Simple.OData.Client to build OData urls:
If the URL that we want to generate is:
{service2}/api/v1/weather_forecast?$select=Description
Then you could use Simple.OData.Client:
string service2Url = "http://localhost:11111/api/v1/";
var client = new ODataClient(service2Url);
var url = await client.For("weather_forecast")
.Select("Description")
.GetCommandTextAsync();
Background, for client-side solutions
If your OData service is a client for another OData Service, then this advice is still relevant
For full linq support you should be using OData Connected Services or Simple.OData.Client. You could roll your own, or use other derivatives of these two but why go to all that effort to re-create another wheel.
One of the main drivers for a OData Standard Compliant API is that the meta data is published in a standard format that clients can inspect and can generate consistent code and or dynamic queries to interact with the service.
How to choose:
Simple.OData.Client provides a lightweight framework for dynamically querying and submitting data to OData APIs. If you already have classes that model the structure of the API then you can use typed linq style query syntax, if you do not have a strongly typed model but you do know the structure of the API, then you can use either the untyped or dynamic expression syntax to query the API.
If you do not need full compile-time validation of your queries or you already have the classes that represent the resources served by the API then this is a simple enough interface to use.
This library is perfect for use inside your API logic if you have need of generating complex URLs in a strongly typed style of code without trying to generate a context to manage the connectivity to the server.
NOTE: Simple.OData.Client is sometimes less practical when developing against a large API that is rapidly evolving or that does not have a strict versioned route policy. If the API changes you will need to diligently refactor your code to match and will have to rely on extensive regression testing.
OData Connected Services follows a pattern where some or all of the API is modelled in the client with strongly typed client side proxy interfaces. These are POCO classes that have the structure necessary to send to and receive data from the server.
The major benefit to this method is that the POCO structures, requests and responses are validated against the schema of the API. This effectively gives you full intellisense support for the API and allows you to explor it's structure, the generated code becomes your documentation. It also gives you compile time checking and runtime safety.
The general development workflow after the API is deployed or updated is:
Download the $metadata document
Select the Operations and Types from the API that you want to model
Generate classes to represent the selected DTO Types as defined in the document, so all the inputs and outputs.
Now you can start using the code.
In VS 2022/19/17 the Connected Services interface provides a simple wizard for establishing the initial connection and for updating (or re-generating) when you need to.
The OData Connected Service or other client side proxy generation pattern suits projects under these criteria:
The API definition is relatively stable
The API definition is in a state of flux
You consume many endpoints
You don't want to manually code the types to serialize or deserialze payloads
Full disclosure, I prefer the connected service approach, but I have my own generation scripts. However if you are trying to generate OData query urls from inside your API, its not really an option, it creates a messy recursive dependency... just don't go there.
Connected services is the low-(manual)-code and lazy approach that is perfect for a stable API, generate once and never do it again. But the Connected Service architecture is perfect for a rapidly changing API because it will manage the minute changes to the classes for you, you just need to update your client side proxy classes more frequently.

OData with WCF Data Services / Entity Framework

Apologies in advance, this is a long question.
(TL;DR : Does anyone have any advice on using the EF with dynamic fields exposed using WCF Data Services/OData)
I am having some conceptual problems with WCF Data Services and EF, specifically pertaining to exposing some data as an OData service.
Basically my issue is this. The database I am exposing allows users to add fields dynamically (user-defined fields) and it uses a system whereby these fields are added directly to the underlying SQL tables. Furthermore, when you want to add data to the tables you cannot use direct SQL, you have to go via an API that they provide. (it's SAP Business One, fwiw).
I have already sucessfully built a system that exposes various objects via XML and allows a client to update or add new entities into SBO by sending in XML messages, and although it works well it's not really suited to mobile apps as it's very XML-heavy and the entry point is an old-skool asmx webservice. I want to try to jazz it up for mobile development and use Odata with WCF or Web API. (I know I could change up to a WCF service, allow handing of JSON-format requests, and start returning JSON data, but it just seems like there must be a more...native...way)
Initially I had discounted the possibility of using the EF for this because a)Dynamic fields and b)the EF could only be read-only; adding/updating entities would have to be intercepted and routed to the SBO DI Server. However, I am coming back to thinking about it and am looking for some advice (negative or otherwise!) on how to approach.
What I basically want to do is this
Expose the base tables from SBO (which don't change except when they themselves issue a patch) as EF Entities, with all the usual relationy goodness. In fact I actually will not be directly exposing the tables, I will use a set of filtered SQL Views as the data sources as this ties in with various other stuff we do to allow exposing only certain data to 3rd parties.
Expose any UDFs a particular user has added as some kind of EAV sub-collection per entity.
Intercept any requests to ADD or UPDATE an object, and route these through an existing engine I have for interfacing with the SAP Data import services.
I suppose my main question is this; suppose I implement an EF entity representing a Sales Order which comprises a Header and Details collection. To each of these classes I stick in an EAV type collection of user-defined fields and values. How much work is involved in allowing the OData filtering system to work directly on the EAV colleciton (e.g for a client to be able to ask for Service/Orders/$filter=SomeUdfField eq SomeValue where this request has to be passed down into the EAV collection of the Order header entity)
Or is it possible, for example, to generate an EF Model from some kind of metadata on the fly (I don't mind how - code generation or model building library) that would mean I could just expose each entity, dyanmic fields included, as a proper EF Model? Many thanks in advance if you read this far :)
For basic crud to an existing EF context, WCF Data Services works out great. As soon as you want to add some custom functionality, as you described above it takes a bit more work.
What you described is possible, but you would need to build out your own custom data provider to handle the dynamic generation of metadata as well as custom hooks into add/update/delete.
It may be worth looking into WCF Data Services Toolkit, it's a custom provider which slaps a repository pattern over WCF Data Services for ease of use, but it does not provide the custom metadata generation.

Convert REST query to Linq query

Is there any way to convert http request query(also known as Web Data Services URLs) as:
Customers(1)/Orders?$ ?$filter=not endswith(ShipPostalCode,'100')
to linq query and execute it against database?
I'm writing a WCF service with entity framework and I need to provide something like data service, but not really..., only in one, two mothods, so I need to parse the http request and execute the linq query against database to get data and then return it.
If it is limited, you could always write your own implementation, see this article
If this is a WCF Data Services (OData) service try Add Service Reference. This will allow for a client proxy using IQueryable interfaces.

WCF. to send data through service and client

I have a service. This service get data from SQL Server.
What the best way to send information to client?
Should I use ADO.NET or Entity Framework?
You can use whichever data technology you want. However, up to Entity Framework 4 in .NET 4 (currently in Release Candidate status), it is recommended not to return an Entity Framework entity or a LINQ to SQL class from a web service. Both technologies unfortunately leak their implementation over the wire - the client-side proxy classes would have client-side classes corresponding to the base classes used by the data framework.
Instead, use a Data Transfer Object, which is an object that has nothing but properties that correspond one-to-one with the properties of the data you want transferred.
From such a brief description it is impossible to say which one is preferred. My personal favourite for such a scenario is Linq to SQL.
If they are both .NET then i say WCF. If server does simple manipulations with data consider Linq to SQL. Or nHibernate.

ado.net data service advantages/disadvantages over WCF service

For me I have a WCF service which acts as DAL and does all the CRUD operations
I just came to know regarding the new ADO.Net Data Service, just read somewhat but not actually sure when & where to use it?
Just to add more, my new project is in ASP.Net MVC, so is it wise to use ADO.NET Data Service rather than WCF service with it which will probably act somewhat like 'M'(Model) of MVC ???
First, my advice would be to write your MVC code so that it is oblivious to what the back-end data model is. Abstract away any dependencies right from the beginning.
As for deciding whether or not to use WCF, I'd suggest that you decide whether or not you'll want to reuse the data component that you write. If you have plans on using your data code in a Silverlight, WPF, or any other format, then I'd suggest sticking with WCF.
Also, remember that you can always simply wrap the ADO.NET data services with a WCF component and still enable the reuse scenario. Get the best of both worlds!
One big advantage is that with the ADO.NET Data Services, you don't have to specifically write all the services for basic CRUD operations as you may with WCF. Since ADO.NET data services basically expose those operations, you can focus more code writing and debugging on business logic.
The big advantage of WCF Data Services, and IMO it fits your need, is when your service layer is used for CRUD only. You do not have (and do not need) any business logic in it.
As Tad pointed out, the reuse is an advantage, but on the other hand, WCF Data Services will give your web app, or any consumer, a very flexible way to query data. With WCF, you'll have to write code to give the consumers the same query flexibility OData gives.
I had a experience recently. I created a service layer with WCF and in many cases, the service operations was used only to call a repository. There wasn't any rule, only query logic. The consumer was able to pass a criteria to have a result back.
The requirements changed and we realized that we could make it more simply (less code to maintain) by using WCF Data Service.