Silverlight: How to consume a REST API? - c#

I'm building a Silverlight app that I want to be hosted in Azure and use Azure table storage.
I have a class that represents the main data entity, ExpenseInfo. It has many data annotations for RIA validation, such as [Required].
I am following this tutorial to set up the REST service for access from SL. It wants there to be a class in my web role for data serialization. This class would contain all the same data as ExpenseInfo.
So, where do I want ExpenseInfo to be? Do I want separate classes in each project? Put it in one project, and instantiate it in both? Is it weird to have a class with all those data annotations in the server side web role?
Thanks, I'm new to SL and Azure.

The pattern you're looking for here is the Data Transfer Object (DTO) pattern. Here's a good article on the pros and cons of that pattern. Personally, I don't mind the additional classes that a DTO and/or and Adapter pattern brings (you will see adapter type patterns used all over the place, MVVM is a hot one right now). I have a strong dislike for sharing business logic in assemblies across a trust boundary, so I generally use DTO/Adapter in my architectures.

Related

Good architecture to shift a WPF desktop application to Client Server technology

I have a working WPF application that works on a single PC. I have used SQL server database, Entity Framework to communicate with database
and RDLC reporting in the application. Now the requirement has arrived to make this application work on the local company network where multiple users (normally around 25 at max) will access application depending upon there roles and permissions set. I did some R&D on this and used primarily the architecture mentioned here http://www.codeproject.com/Articles/434282/A-N-Tier-Architecture-Sample-with-ASP-NET-MVC-WCF, and after doing so, I have made a paper design/architecture of the application that will look like this
A WCF service running on a high end server within the company network
GPC.Service itself - defines the protocol to connect to the service
and all other necessary information
GPC.Algorithm - will be the main business logic layer that will
contain the logic and will be interface to the clients for calling
the database layer methods
GPC.Persistance - will have actual database interaction methods like
fetching/storing/updating/deleting records in the database
GPC.Data - This will contain the edmx schema for the Entity
Framwework
GPC.Entites - This will contain the entities of the database schema
and addional partial classes
**
Clients:
The client will a WPF Application based on MVVM pattern for now (may be in future we will need to move to the Web application but not required for now). Main components of the application are:
Import from excel: Currently all data is in Excel files. All that
data needs to be imported into the system.
Edit/Update/Delete: Once data is imported, allow interface to user
to edit/update/delete records
Generate reprots (using RDLC for this)
Users/Roles management etc.
Shared:
This is a library that contains differnet miscelenious classes like code to read excel file, Handle errors, Collections that will be bind to the UI etc.
DB context: Will be created in a using statement inside the Persistance layer for each method to ensure no stale information is left.
Does this architecure follow the n-tier architecture and is it flexible? What improvements are required in this and please guide me how to improve whatever issues are there. I want to make sure this is a good architecture before I go ahead and change my existing application.
It seems like your are on the correct path however you may be over engineering in some areas.
I think to a large degree the EntityFramework deals with the Entities, Data and Persistence layers for you. Implementing them yourself may be overkill unless you are looking to ultimately replace EntityFramework with some other ORM system.
You are eluding to SOA (Service Orientated Architecture) here with your GPC.Services library. Here you need to look at how you can break down your service layer into one or more atmoic services which will serve the client application. There are a number of ways of going about this and would depend largely on how you plan to use the service layer going forward. Take a look at RESTful services which breaks down the services layer nicely and will guide you into building neat atmoic services. Check out the Asp.net Web API for this.
I think what you are looking for in your GPC.Alogrithms library is really a domain model. A domain model encapsulates all your business logic and allows you to perform state changes on your objects via public functions which you expose. With this in mind the layers of the system would appear as follows:
Persistence (EF) -> Domain Model -> Service Layer -> DTO (Data Transfer Objects) -> Client
The DTO objects mentioned above would be a set of POCO (Plain Old C# Objects) which are responsible for delivering data to and from your client. You need this since serializing and desalinizing your domain objects will become problematic due to back references and other encapsulation issues. Putting DTO's in place will enforce a context boundary which is once of the tenets of SOA - "Boundarys are explicit", see this for more info on soa
With respect to the client side it seems like you are on track. What you may want to do is refactor you current client application so that all data queries are consolidated into a single layer. So when the time comes you will just replace that layer with the service implementation.
this makes perfect sense. (try to build it TDD style)
in order to make your life a bit easier with the client versions management consider to use ClickOnce installer to enforce the latest version installations on your users computers (this headache will be gone once you will move it to be a web app).

N-Teir Architecture with ASP.NET Web API

I'm just trying to wrap my head around this concept. I have written a couple different Web APIs but they have always been consumed by a website and interacted via JSON. I have a question about how to structure the implementation when the Web API will be consumed by a windows service.
In this case there is already an existing Database so I want to use Entity Framework's Database First approach.
I create a Class Library project for the models and use Entity Framework to look at the existing database and generate all of the required classes.
Then I create a Web API Project and add my Class Library with all of the models to it. Up to this point I am good.
My question is when I go to build the Windows Service that will interact with the Web API, how do I access the classes from my Class Library model project? I know I could add that project to my windows service but that doesn't seem like the correct approach because that would pretty much by-pass the Web API.
I guess my question is if I want to create and pass an Employee object to my Web API (so it can insert it into the database) from my windows Service, how does the windows service get the Employee object without adding the Class Library to the Windows service project?
In an n-tier solution you don't pass domain objects across physical boundaries, but you implement data-transfer objects (DTO) that will only hold the required info by the consumer/caller.
Usually you're going to created a shared library that will have the whole data-transfer objects and this will be referenced both by the server and the client.
After that, it's all about using a JSON serializer in order to serialize and/or deserialize your data-transfer objects.
Domain objects will be always mapped to data-transfer objects because these are lighter than a full object. Make yourself a question: if the consumer only requires the name and the second name of someone, why you need to send more data over the wire?
In addition, it's important to avoid server dependencies in client applications and services.
Some useful tips:
Learn what's a DTO: http://en.wikipedia.org/wiki/Data_transfer_object and http://martinfowler.com/eaaCatalog/dataTransferObject.html
Check AutoMapper and how can save you time in order to map domain objects to data-transfer objects: http://automapper.org/
Normally you create exra model classes that are used for the Web API. Those model classes often contain only a subset of the data of the entities. Furthermore, this distinction allows you to create truly RESTful APIs.
Inside your Web APIs controller classes the mapping between Model and Entity happens.
The windows service only referenes the project with the Model classes but not that with the Entity classes.

Switchable XML and SQL backend

I have an architectural question, we need to develop information system with two frontends: lightweight web-app (ASP.NET) and desktop (WIN-FORMS) app. Nothing special so far, but these two frontends should be able to communicate with two shared and switchable (after app restart) database backends, one SQL database (SQL server) and one, most probably, some kind of XML store (everything in one file would suffice). These two stores won't be synchronized.
Both applications will be very simple, only few forms.
Please, is there any out-of-the-box stuff, e.g. in Entity framework, which can be tuned as described above?
Or what architectural design would you recommend?
Hmm.
Your best bet is to have a class library project for your data repository.
Give it a known interface and use a factory pattern to decide at runtime whether it generates a SQL instance or a XML instance.
Best have the repository based on a singleton pattern.
Thus you'd have something like Repository base inheriting IRepository, with XMLRespository and SQLRepository inheriting from Repository.
Your business logic then just refers to IRepsository or Repository and doesn't care about what is actually there (XMLRepository or SQLRepository).
This is similar to the Repository pattern.
If you want to use the same business logic with different front ends and your sticking to ASP.NET Webforms and Winforms then I'd do the same with the business logic i.e. place it into a class library and call from ASP or Winform code as necessary.

Using collections/lists within WCF DataContracts

I don't know very much of WCF...
I want to do a clean job to serve entities on client side using DataContracts. Imagine two DataContracts "System" and "Building": "System" may have many "Buildings" and "Building" may have many "Systems". So, we have a many-to-many relationship between them.
In service contract model, "System" have a "Buildings" property that is a collection. "Building" also have a collection of "Systems".
The WCF uses DataSets for the underlying data access (with stored procedures for CRUD) and I have a table between SYSTEM and BUILDING representing the relationship.
So, how can I implement this scenario cleanly? I want the clients to be able to get a simple representation of "Buildings" in "System", for example, I could use:
system = GetSystem(id);
foreach (Building building in system.Buildings) {
// do whatever with each buildings...
}
Thank you!
I think this question is too broad to cover in full detail, but I can give you a few pointers to get you started.
Forget about WCF and build the Data Access Layer (DAL). This should be a library which contains code to query the database and return strongly typed objects. This library might contain a method called GetBuildings() which returns a list of Building objects. The library might work with DataSets (and other database specific types), but should not expose DataSets to external callers.
Now that you have a library which can be used to get data from the database, write the WCF service. Code in the service component should call into the DAL and turn that information into DataContract objects to be sent over the web service boundary. Don't try to represent all your data in the DataContract objects - you want your data packets to be relatively small, so don't include information that isn't required. Balance this with trying to make as few web service calls as possible. In designing your DataContract classes, consider what the client application will be doing with the data.
Write the Service Client component. This is code which makes calls to the WCF Service, and turns that information into Entity objects.
The final (and most rewarding step) is to write the client application logic. Now you have another set off issues to confront about how you will structure client code (I recommend using MVVM). The client application should call into the Service Client component, and use the data to meet the requirements of your application.
By following the above 4 steps, you should end up with:
A Data Access Layer that talks to the database.
A Service Layer, which knows nothing about the database but is able to fetch data from the Data Access Layer.
A Service Client layer, which knows nothing about databases but knows how to fetch data from the Service Layer.
Application code, which knows nothing about databases or web services, but calls into the Service Client layer to get data and presents the data to a User Interface.
Everyone will do this differently, but the main thing is to separate concerns by using a layered architecture.

Models just in a WCF Service or is it necessary a replica in the Client?

I am building an application. I am creating a Silverlight 4 client with the help of MVVM Light. I am acquiring data from a WCF Service. At least, this is the plan.
In the WCF Service I have defined the "entities" that I need to use in my application. When in the Silverlight Client I add a reference to my WCF Service, Visual Studio recreates on the client-side all classes that were marked with the attribute [DataContract] in the service.
What I would like to know is if this is a bad practice and if it were better to create the Models inside the Client. As far as I understand, in the first case I should only create the ViewModels and the Views in the Silverlight client, whereas in the second case I should create the Views, ViewModels and Models inside the Silverlight client, and populate the Models instances with the values coming from the WCF Service.
Thank you for your help.
Cheers,
G.
UPDATE
Ok, I don't think my question was clear enough as I havent not received many feedbacks.
However, I'd like to provide an update on this. The answer I was looking for is "No! Data Transfer Objects!".
I was thinking to use my entity classes (the ones mapped to the DB tables) as DataContract in a WCF Service. Adding a reference to this WCF service in a client would have created all the classes decorated with DataContract on the client too.
The big problem in my case is that the data layer is based on Hibernate, which soemtimes makes extensive use at runtime of "data proxy" classes (see Castle Proxy). Well, it turned out that there is a serialization issue with these data proxies, and as far as I understood the best approach is to adopt the Data Transfer Objects pattern in order to map the "complex" entities to a similar but "lighter" class (the DTO).
I hope this can help someone else.
Have a nice day!
Gianluca.
Have you looked at WCF RIA with Nhibernate? To try and answer the question though: I wouldn't try and return entities from the WCF service directly, I personally would create DTO's. And then I would probably map those DTO's to some sort of a client side model. So, that's what I would try and do if I wasn't able to take advantage of RIA.

Categories

Resources