I am writing an Class Library as DataModel. DataModel capable of handling all the Database related task. I am using NHibernate and Fluent NHibernate for the same.
Now the question arises are as follows :
Should we expose the Entity (POCO Class).
Is it good to have a Entity with internal protected property and property exposed as a interface.
Entity created for mapping can be a Model for WPF MVVM.
Or should we directly bind entity ?.
There is no control if Library returns a List of entity as API return. So anybody can do add or delete in list. How should I keep control on it. Should I create proxy derived from IList which will keep track of it.
Is it right to throw Exception occurring in an API or should I return null?.
Is it good keep logging in the Library ?.
Should we expose the Entity (POCO Class).
Yes, Creating wrapper class makes more effort.
Is it good to have a Entity with internal protected property and property exposed as a interface.
Yes, Setter and non-exposed properties are control.
Entity created for mapping can be a Model for WPF MVVM.
For primitive type can be, but reference can be exposed by interface.
Or should we directly bind entity ?.
If Model is created rather directly use of POCO object. It is much more flexible for refresh cases. User can not change property of POCO object if cancel operation is there.
There is no control if Library returns a List of entity as API return. So anybody can do add or delete in list. How should I keep control on it. Should I create proxy derived from IList which will keep track of it.
IEnumerable is used to exposed collection by interface.
Is it right to throw Exception occurring in an API or should I return null?.
Exception is much more better to make know to user about error. but wrap the exception in user readable rather returning NHibernate exception.
Is it good keep logging in the Library
Logging is very good feature to know about issue.
Should we expose the Entity (POCO Class).
yes, otherwise whats the use of the entities when nobody uses
Is it good to have a Entity with internal protected property and property exposed as a interface.
It depends! internal protected properties are no problem when using an ORM but i prefere to reduce internal stuff to a minimum because i like objects maintaining their own state. interfaces are fine
Entity created for mapping can be a Model for WPF MVVM.
of course. No need to duplicate them another time. That's what persistence ignorance is for
Or should we directly bind entity ?
More ofthen than not, the UI requirements are very different than persistence/businessrules so there will be specialised ViewModels for UseCases/Views. However simple Dataholders like Order class thrown into Lists can be bound directly (e.g. using a DatabindingFactory to make them implement INPC)
There is no control if Library returns a List of entity as API return. So anybody can do add or delete in list. How should I keep control on it. Should I create proxy derived from IList which will keep track of it.
Lists are just in memory container. The user still has to go through the API to Save/Update state.
Is it right to throw Exception occurring in an API or should I return null
if collections are returned then empty collections are far better than null.
Exceptions however should bubble up preferably wrapped in own handable Exceptions. Implement NHibernate.Exceptions.ISQLExceptionConverter (e.g. like NHibernate.Test.ExceptionsTest.MSSQLExceptionConverterExample) and configure it with e.g.
config.DataBaseIntegration(db => db.ExceptionConverter<MyExceptionConverter>())
Is it good keep logging in the Library
absolutly. Logging enables debugging deployed applications. (Fluent)NHibernate already has lot's of logging built in use it if possible.
Related
I come from Grails background and have recently started a project in Micronaut using GORM.
I tried to find required information in documentation but its not clear how we retrieve post data in controller, validate it similar to Command Objects offered in Grails and save it into database using interface service provided in documentation
PS : I know I can map every field to action argument in controller, and also declare a interface method specifying each argument as property but that does not seems right thing to do as my domain class has so many properties.
Making the action #Transactional or any method would work for saving data as far as I know but I want to know the proper way in Micronaut.
My requirement is simple, save post data in database using GORM in Micronaut.
If I were you I would look back at the documentation, sections 6.4 to 6.11:
https://docs.micronaut.io/snapshot/guide/index.html#binding
https://docs.micronaut.io/snapshot/guide/index.html#datavalidation
http://hibernate.org/validator/
Micronaut is very annotation based, unlike Grails which uses convention over configuration. However in Grails 4, Micronaut will toke over the application context, giving you some of the benefits of Micronaut, but still maintaining the convention over configuration.
I have a set of Services that I want to use in various ServiceStack projects (okay, two) so I have created a ServiceStack Plugin that registers them.
However I want to allow users to determine their own method of securing access to these services.
Currently I have an IHasRequestFilter in one my projects that can determine which services a user should be able to access. I do not want a reference to this in the Plugin project, so I want to add this dynamically after the fact.
I want to somehow get a reference to the Service Definition in AppHost to add this IHasRequestFilter to the pipeline for a specific set of services.
Ideally I should be able to do something like this:
new CustomPlugin(new CustomPluginParams {
RestrictTo = CustomRestrictions,
RequestFilters = [],
ResponseFilters = []
});
This should use those properties to configure their services without having a previous typed reference.
Edit:
Investigating further it appears that the IHasRequestFilter and IHasResponseFilters are only parsed once, in the ServiceExec<TService> class. I could get round this by creating my Services with a Proxy which adds the attribute I require to the MemberInfo of the operations, however I don't regard that as a clean approach.
Does anyone have recommendation?
In ServiceStack all configuration should happen within AppHost's Configure() method and remain immutable thereafter.
Lifecycle Events
To help with LifeCycle events there are IPreInitPlugin and IPostInitPlugin Plugin Interfaces which your Plugins can implement so they will get called back before and after all plugins are registered.
There's also an IAppHost.AfterInitCallbacks plugins can use to get called back after the entire AppHost has finished initialiazing.
Typed Request/Response Filters
Attributes are typically statically defined on Services, to dynamically add logic that apply to specific Request/Responses you can use a typed Request/Response filter.
The nice thing about ServiceStack Filters is that they share the same API (IRequest, IResponse, object) which makes them easily composable, e.g:
RegisterTypedRequestFilter<CustomRequest>(new RequestAttributeFilter().Execute);
Dynamically adding Attribute filters
As all ServiceStack libraries use ServiceStack.Text's Reflection API's you're able to extend ServiceStack's attribute-based code-first API dynamically by adding attributes to types or properties at runtime, e.g:
typeof(CustomRequest)
.AddAttributes(new RuntimeAttributeRequestFilter());
This can be done for most of ServiceStack's code-first API's inc. Request/Response Filters.
Route attributes and Action Filters
There is sometimes an issue for Services Route attributes and Action filters that already pre-configured and autowired before the AppHost's Configure() is called.
One solution is to add them in the AppHost constructor (or by overriding AppHost.OnBeforeInit) so they're added before the Services are configured. Otherwise you can reset the action filter caches by calling the AppHost's ServiceController.ResetServiceExecCachesIfNeeded().
I am using RestKit .22.0 with Core Data integration, both of which I'm pretty unfamiliar with. I followed the RKGist tutorial and was able to learn how to get objects from a REST endpoint, set up object mappings, add routes, and see the data from the web service correctly insert into the Core Data sqlite database.
Now I'm starting to work on persisting objects to the web service, but can't find any information on how best to do this. It seems like there are multiple ways to skin a cat with RestKit, so I wanted to see what the best practices are for POST/PUTing data.
When POSTing a new object, do you usually save the object in the managed object context first, then call [[RKObjectManager sharedManager] postObject:path:parameters:success:failure:]? Or is there some RestKit method that performs both of these operations at once?
If you first save the object in Core Data then POST it to the web service, is RestKit going to be able to update the already inserted object with the service's database identification attributes? Does the [[RKObjectManager sharedManager] postObject:path:parameters:success:failure:] method do this for you?
If there was an error POSTing the object, what is the typical way you'd retry the POST? Would you look for some sort of flag in the core data managed object and retry in a separate thread?
Thanks!
Yes, then the response from the POST updates that same object (perhaps filling in the server specified unique id)
Yes, updating the POSTed object is the default behaviour (you need to specify the response mapping and the response must be a single object)
No separate thread generally, and it depends what caused the error. Have a flag that indicates it's uploaded and retry when network connection is reestablished
We have a working website using ServiceStack as the back end that amounts to a complex data-entry form.
My users have requested an "offline editor" for the forms. To use the offline program, the user will have to connect to the ServiceStack service, create empty instances of the forms, and then I will save the POCOs from the service to disk using ServiceStack's JSON serializer. From there the user can log off the service and edit the POCOs. When they're done, they reconnect to the service, and post/put the edited POCO object.
This all works great. My question involves validation. The validation logic is built into my Service.Interface library, which isn't available offline. The winforms program references only the POCO library and the ServiceStack "common" libraries, which do not look like they include the ServiceStack.Validation namespace.
Is there a way I can rearrange my project so that both the service and the Winforms client can run Validation against the POCOs, so that they can have data validation while offline?
UPDATE:
getting closer, I think - I moved all of the Validation classes into their own project. From my Winforms project, I can now manually set up a validator for a POCO class like this:
ServiceStack.FluentValidation.IValidator<SomePOCO> IValidator;
IValidator = new Tonto.Svc.Validation.SomePOCOValidator();
ServiceStack.FluentValidation.Results.ValidationResult vr =
IValidator.Validate(_rpt);
I can see the validator constructor being set up and the rules being initialized, but the .Validate method doesn't seem to do anything. (object comes back as valid, and breakpoints into custom validator code never get there).
UPDATE #2
I discovered my validator code wasn't running from Winforms because my validators all specify a servicestack ApplyTo Put/Post only (see sample code below). When I remove the entire Ruleset clause, though, then validation happens in my service on GETs - something I never want.
Can anyone think of a way to configure the validator rules to run for POST/PUT only when called from ServiceStack, but to also always run when NOT in servicestack? So close!
public class SomePOCOValidator : AbstractValidator<SomePOCO>
{
public SomePOCO()
{
RuleSet(ApplyTo.Put | ApplyTo.Post, () =>
{
(rules)
});
}
}
If your validation is doing anything interesting, then it probably HAS to be done "online".
Maybe just allow your client to save the POCOs locally until they go back online, at which point you send them up to your server. Any transactions that are okay, get processed normally, and any that fail, get returned for the user to edit (so your client will need some smarts to have a working set of POCOs for editing)...
If you don't want ANY extra stuff on the client, just have the transactions that fail to validate get stuffed into a "needs_corrections" table on the server, and then code up a supervisor-sort of screen to manage that table.
The validation framework that ServiceStack uses is named FluentValidation. There is no WinForms support in it. Jeremy Skinner the creator of FluentValidation answerd a question about this back in 2010 on his forum here.
Personally I don't use FV with WinForms - the vast majority of my projects are web-based with the occasional WPF project.
However, if I was going to do this then I probably wouldn't validate the controls directly, but instead use a ViewModel which is bound to the controls. I'd use a fairly strict convention where the names of the controls would match the names of the properties that they're bound to. Then, after validation completes I'd walk the control hierarchy to find the control with the name that matches the property that failed validation (I'm not sure how you'd do this in WinForms, but in WPF I'd use LogicalTreeHelper.FindLogicalNode) and then use the ErrorProvider to set the appropriate error.
Jeremy
I was able to work out a solution that allowed me to use ServiceStack validation libraries on both a ServiceStack client and an offline client. Here are the details.
Move all AbstractValidators to their own project: Proj.Svc.Validation.
get rid of all RuleSets in your AbstractValidators.
Reference Proj.Svc.Validation from Proj.Svc.Interface and Proj.OfflineWinformsClient projects.
Turn OFF the ValidationFeature() plugin in your service. All validation will have to be done manually. This means no iOC injected validators in your service classes.
When it's time to validate, either from your service or the offline client, manually declare the validator and use it like this.
IValidator validator = new
Tonto.Svc.Validation.SomePOCOValidator();
ServiceStack.FluentValidation.Results.ValidationResult vr =
validator.Validate(poco);
if (!vr.IsValid)
(throw exception or notify user somehow);
I am new to DDD but I am trying to implement it in my Project - I have a service which is setup following the DDD principles - Application / Model / Repository - The Clients of the Service want to get back a DTO class (which also contains a Error Collection as one of its members) . Questions is how do I populate the Error Collection of the result DTO. Can the Error DTO be passed from the Application/Service Layer to Model/Service layer and populated there – Can someone point me to some example of these kinds of scenarios Currently I am bubbling up all the errors that I am getting back to the Application Service and populating it there like I said I am struggling.
As a general rule try not to copy code (classes, methods, interfaces). If you really have to use DTOs create them as late as possible in the process so that if you remove them you should still be able to use the system in another way.
I would have something like this:
Model
Domain classes
Error class
Model/Service (has reference to Model)
Application/Service (has reference to Model and Model/Service)
Domain DTOs
Error DTO
Also a question do you really need two Service Layers? Avoid Anemic Domain Model