I share a Data Transfer Object between an C# Azure Mobile Services server and client. I use the same class in both applications.
The TableController class used by Azure mobile services requires the DTO to inherit from 'EntityData', which in turn implements interface 'ITableData'.
ITable Data lives is part of reference:
Microsoft.WindowsAzure.Mobile.Service.Tables
I have not figured out how to include that reference without installing the entire server-side mobile services package in nuget:
WindowsAzureMobileServices.Backend
That includes OWIN, and many other references the client does not need. This is what I am doing currently. This works for a desktop application I am currently working on, but I think it will not work for universal apps and windows phone apps.
I also looked at microsoft's samples for mobile services, and there they use separate classes as DTOS for server and client.
Is it really the case that we have to write the same code twice?
No, but you could better make use of Shared Projects, and partial classes.
Your Shared Project will have common properties for the entities.
Other projects will reference this Shared one, and can add some other properties to shared entities, still using partial classes.
I have precise experience with AMS, so I know what you are meaning.
In my experience, is anyway not realistic to think to have exactly the same entity classes for client and server.
For instance, in so called Portable Class Libraries you can have a very small subset of framework, and references available.
Other than properties, you normally put attributes on POCO class files. On the client you may have some attributes that aren't available/meaningful for the server (e.g. SQLite attributes), or viceversa. You may can get stuck in this situation also with the shared projects approach I suggest, but it could be managed there with what so called preprocessor directives.
Related
My layout
project.web (.net core 2.1 web api)
Some binding models (for post/put requests) and resource models for GET requests
Controllers.
I only call interfaces from (x.api) which are resolved to x.core services.
No validation or anything. This happens inside the core layer
I've setup a few things like automapper and swagger, that are not relevant for my question.
project.api (class lib)
only contains interfaces for .core and .store projects (services, repositories and domain models)
project.core (class lib)
two kinds of services
1) Services which call the repository services (interfaces). But validate the data before calling the repo service.
2) Services that will have to execute long term stuff (IE: scanning folders, handling file information, ...). I actually created HostedServices for these as a folder could easily contain thousands of files.
project.store (class lib)
Wrapper services for my storage (Only contains helper methods so I don't have to write the same queries a hundred times.)
Problem / question
At this time I have registered all of my services and repositories as singletons in public void ConfigureServices(IServiceCollection services)
because I was using a different storage (nosql, litedb) before refactoring code to EF (sqllite)
Now the problem is that I want to register my DbContext as scoped (by default)
But my repositories (singleton) depend on dbcontext. Which means I will have to make these scoped as well. I'm ok with this, as these are only wrapper services, so I don't have to write the same queries all the time.
But some other services, that will need access to my data are singletons, and I cannot register these as scoped. Contains some data that needs to be the same for every request, and some collections and long running jobs.
I can think of two solutions
The first solution is to make a dependency to IServiceScopeFactory in my repository and use something like using (var scope = ServiceScopeFactory.CreateScope()) { scope.ServiceProvider.GetService(typeof(MyDbContext))... }
this way I can remove the dependency from my repository wrapper, but this doesn't sound clean to me.
The other solution is to register all of my services that only handle database stuff as scoped. (IE customerSservice in core only does validations and calls customerRepository) I remove dependencies from my remaining singleton services.
In those singletons, instead of depending on the customersService, I could use a rest call with restsharp or something similar
Just like how I would consume them from my windows client applications and web client apps.
I don't actually like either. But perheps someone can give me some advice or thoughts?
Well, the two options you laid out are in fact your only two options. The first is the service locator antipattern, which as the name implies, is something you should avoid. However, when you are dealing with singleton-scoped objects needing access to objects in other scopes, there is no other way.
The only other option is to reduce the scope of your services from singletons, such that you can then inject the context directly. Not everything necessarily needs to be a singleton. Generally, if you need to utilize something like DbContext, there's a strong argument to be made that your object should not be singleton-scope in the first place. If you need it to be singleton-scoped, that's most likely an indication that the class is either doing too much or is otherwise brittle.
I created a WCF service in charge of exposing my database's data since I don't want the database to be directly accessed by my application (for security reasons) and i need to be able to share data with third-party applications.
My solution is structured this way: WPF application -> WCFService library -> DataAccessLayer library. (Arrows define assembly dependencies 'depends on')
To implement the WCF service I considered to simply return detached EntityFramework objects from the service BUT it forces the main application to have a dependency on the DataAccessLayer library.
The only way i can get around that is generating POCO objects and use them to send them over the wire, but now i have to map values back and forth EntityFramework.
At the moment i'm generating POCOs dynamically via a T4 template and I'm using AutoMapper to map values back and forth EntityFramework.
The Wcf service will just have to implement the repository pattern to expose data.
Is this a good solution? Are there any other option?
Is there any shortcoming i should be aware of?
Depending on your constraints, I would have to agree with this solution.
I created an almost identical solution, although our motivations were slightly different. Our client was Delphi Win32, and at the time didn't have good support for JSON, so we had to use SOAP.
The client also didn't support nullable primitives, so the POCOs removed all unsupported types, and performed other changes to ensure interoperability, then we used Automapper custom mappings to handle the two way conversions.
All the WCF services (contracts and implementations) where also generated by T4 templates, using a generic repository. With T4 templates, I was able to generate a separate WCF service per table for CRUD operations, and then manually created WCF services that were business specific.
Finally, I was also able to used T4 templates to generate the Delphi repositories that interacted with the SOAP services.
Or
You could just as easily move the POCOs (and code generation) to a separate project, change your DataAccessLayer library to reference the POCOs library and only contain the Db context made up of DbSets of your POCOs, and Data access logic but no entities (which are now POCOs). Your clients will not need to have a dependency on the DataAccessLayer library.
So... a good solution, depending on your constraints.
I am an experienced .NET/C# developer but new to pretty much all of the technologies/libraries here including SQL/DB work.
I am developing a project with an Azure/Entity Framework .NET backend and portable .Net APK for consumption in a number of other projects. I am trying to follow recommended practices and guidelines, but it's surprisingly hard to find documentation. I find myself repeatedly feeling like I'm fighting against the system, and slowly beating out a seemingly endless succession of fires with a blunt table spoon.
I find myself wondering if the overall architecture I'm using is the fundamental problem here. I prefer to pretend I'm not merely incompetent.
Current Structure
DTO contracts project
Interfaces for the DTO classes shared between the other two projects
Backend project
Implementations of the DTO interfaces + conversion to/from model classes
Code first database model classes
TableController<SOME_DTO_CLASS> implementations
ApiController for non-query operations
Portable SDK library project
Implementations of the DTO interfaces + conversion to/from SDK classes
SDK exposed classes for use from other applications
Service class that wraps MobileServiceClient and IMobileServiceTable and exposes SDK classes
Motivation/Implementation
Contract interfaces
The motivation for the DTO contract interfaces is to get as far away from magic strings / relying on member names as possible. These are interfaces rather than classes because TableController<T> requires implementations of ITableData, which is not available for use in the portable DTO contracts project.
Backend
The TableController<SOME_DTO_CLASS> classes GET methods currently refer to the current context (NOT this.Query()) and .Select() to create matching instances of the DTO classes. Lazy-loading is intact. These GET methods apply a .Where() with this.User to filter out only those entities the user has permission to access.
The Code-First model entirely derives from EntityData, even if the class is not going to be exposed via a TableController<T>. Navigation properties are used to types that are NOT exposed via their own TableController<T>. The fluent API is used to describe relationships.
The DTO classes expose their relation properties as the interface types rather than their concrete types because that's how interfaces work.
SDK
Currently this uses IMobileServiceTable but will likely switch over to IMobileServiceSyncTable at some point.
The DTO classes expose their relation properties as the interface types rather than their concrete types because that's how interfaces work.
Current flaming spoon target
Right now I've got the SDK successfully exposing it's own SDK types pulled down from the database. DB model -> DB DTO --> *MS Code* --> SDK DTO -> SDK exposed class all works.
Sort of.
The DB DTO classes' properties that expose other DB DTO classes appear to be ignored in transmission despite being part of the IQueryable returned in the GET method. I cannot retrieve them using $expand= as apparently The specified type member 'TestClass' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. This still occurs if I switch from interface property types to concrete ones.
I could potentially avoid this issue by only including foreign key IDs and fetching linked entities separately in the SDK, but that seems highly inefficient and somewhat very nope.
Get to the question you 4AM fool!
Dis gud?
More specifically (and formally) is this current project structure reasonable and likely to be sustainable? Are there any obvious flaws or oversights that will prevent this from working?
Assuming this is reasonably reasonable, what is the proper way to tackle the DTO $expand issue?
The $expand attribute is the way to go, but unfortunately the Azure Mobile client SDK blocks this in the query string. It will be fixed in the future, but for right now your best bet is to use an attribute on the server side to add the query string on incoming requests.
For an example of this, see https://github.com/paulbatum/FieldEngineerLite/blob/master/FieldEngineerLite.Service/Helpers/ExpandPropertyAttribute.cs. The sample is for Azure Mobile Services, but that code can be easily applied to the Azure Mobile Apps server SDK.
I developed a REST API with Play 2.2.0. Some controllers expose GET methods, other expose POST methods with authentication etc...
I developed the client using Play as well but I have a problem. How can I avoid duplicating the model layer between both applications ?
In the server application, I have a Model Country(code, name).
In the client I am able to list countries and create new ones.
Currently, I have a class Country in both sides. When I get countries I deserialize them. The problem is that if I add a field in Country in the server, I have to maintain the client as well.
How can I share the Country entity between applications ?
PS : I don't want to create a dependency between the API and the client, as the client could have been developed with another language or framework
Thanks
This is not very specific to play framework but is more of a general question. You either create reusable representations of the data in your protocol (the actual data structures you send between your nodes) and get a tight coupling in representation and language. Many projects does it like this, since they know they will have the same platform throghout their architecture.
The other option is to duplicate all of or only the parts of parsing/generating that each part of the architecture needs, this way you get a looser coupling and can use any language in the different parts.
There are also some data protocols/tools that will have a representation in a protocol specific way and then can generate representations in various programming languages.
So as you see, it's all about pros and cons - neither solution is "the right way (tm)" to do this, you will have to think about your specific system/architecture and what pros are most valuable and what cons are most costly to you.
Well I suggest to send to the client a template of what they should display, on the client with js take advantage of js template frameworks, so you can tell to the client how can show them, dynamic... if they want to override them well... more job
We can call them Rest component oriented...
well suggestions :)
should works!
In a MVC application, what are some of the components that make up the application. What tools and functionality is missing that you would like to have. Regardless of the server-side language, what would you want?
I see a lot in my code where I code some much functionality that it seems should already be there. I looked at Google web toolkit and they seem to get it right. Widgets are widgets and you simply add them to your application.
For example. I work with J2EE apps but in other languages, the components are the same.
Controller Objects
Controller handlers, defined by methods in the controller objects.
Configuration files defining the URL mapping and settings.
Template server page files (e.g. JSP/ASP files).
Configuration files defining O/RM mapping between application objects and the database.
Configuration files defining the database connection properties.
JavaScript libraries (e.g. jQuery)
Logging configuration files
Resource message bundle files
Validation configuration files or code
Middleware components and objects (EJB configurations, JMS/Messaging configurations, etc).
Credit Card or other middleware connectivity APIs and libraries.
Anything else you can think of?
Built-in Unit Testing Component
I think one thing you're missing from that very exhaustive list is the automatic binding of request properties to form objects, and the saving of these objects to the session where appropriate. Form objects here being the object on the server that represents the current state of the HTML-based for displayed to the user.
I think scaffolding and automatic admin interfaces are very nice features too, that I dont want to miss ;)
You've made the assumption that all MVC applications are websites. MVC is widely used for more than just web apps so things like URL mappers, template server pages and "Server side" languages are not associated with the MVC pattern, so much as a particular implementation and adaptation of the MVC for use in web apps.