I'm currently working on an MVC 3 project which uses Fluent NHibernate. I utilise the System.DayOfWeek enum but when mapping this I received the following error -
Stack Trace:
[MappingException: Could not determine type for: DayOfWeek, for columns: NHibernate.Mapping.Column(WeekStart)]
NHibernate.Mapping.SimpleValue.get_Type() +456
NHibernate.Mapping.SimpleValue.IsValid(IMapping mapping) +40
NHibernate.Mapping.PersistentClass.Validate(IMapping mapping) +123
NHibernate.Mapping.RootClass.Validate(IMapping mapping) +24
NHibernate.Cfg.Configuration.ValidateEntities() +280
NHibernate.Cfg.Configuration.BuildSessionFactory() +43
FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() +54
[FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory.
Check PotentialReasons collection, and InnerException for more detail.
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET
Version:4.0.30319.272
Example usage -
Map(x => x.WeekStart).CustomType(typeof(DayOfWeek));
I've seen this specific question asked on mailing lists and on stackoverflow but the nuances of it never seemed to be fully grasped and the person asking the question is referred to how to use a custom type mapping.
I am well aware of how to use the customtype functionality on fluent maps and frequently make use of it. However I don't understand why this enum in particular cannot be mapped. I presume it has something to do with the System namespace to which it belongs?
If anyone can shed any light on this I'd be most happy.
Thanks
I got the mapping of DayOfWeek enum to work with this mapping.
mapping.Map(x => x.DayOfWeek);
and its maps fine to a nvarchar(255) in my mssql database.
My property looklikes this
public virtual DayOfWeek DayOfWeek { get; set; }
I use NHibernate version: 3.3.1.4000 and Fluent Nhibernate version: 1.3.0.733
As with any enum mapping with NHibernate, save yourself some grief (dirty reads which cause unnecessary writes, different type specified in database, etc.) and just always use a PersistentEnumType.
In this example, create your PersistentEnumType:
public class NHibernateDayOfWeekEnumMapper : global::NHibernate.Type.PersistentEnumType
{
public NHibernateDayOfWeekEnumMapper()
: base(typeof(DayOfWeek))
{
}
}
Then use it to do your mapping:
Map(x => x.DayOfWeek).CustomType<NHibernateDayOfWeekEnumMapper>().Not.Nullable();
Now you've got the entity that doesn't dirty read (and so no unnecessary writes) and a correct type mapping in the database (when you use SchemaExport to generate your schema).
For more information see an oldie but goody at http://eashi.wordpress.com/2008/08/19/mapping-enumeration-of-type-int-in-nhibernate/
Related
first of all, if any developper of the lib spring-data-cassandra read me : Thank you for your work, the lib is working like a charm and is well integrated to spring project.
Here is, a few days ago i was facing a problem when trying to use pagination in cassandra. I found a workaround to my problem and will explain how did i do that.
My problem is the following, i've been using pagination for cassandra and i've had to iterate over the slices of results and it worked until i decided to use Sort in pagination.
To achieve that i've used:
-a service using a Repository extending CassandraRepository
here is the code (the service wrapping the repository)
public Slice<Pony> getAllByTypePage(Pageable p, EnumType type) {
Slice<Pony> slice = ponyRepository.findAllByType(p.first(), type);
//Iterate over slices
while(slice.hasNext()&&slice.getPageable().getPageNumber()<p.getPageNumber())
{
slice = ponyRepository.findAllByType(slice.nextPageable(), type);
}
return slice;
}
Pony is my Model en ponyRepository is my CassandraReposity
#Repository
public interface PonyRepository extends CassandraRepository<Pony,UUID> {
#Async
CompletableFuture<Long> countByType(EnumType type);
Slice<Pony> findAllByType(Pageable p,EnumType type);
}
When i try to get a page (other than the first one) i get this exception
com.datastax.driver.core.exceptions.PagingStateException: Paging state mismatch, this means that either the paging state contents were altered, or you're trying to apply it to a different statement
after some debugging i've seen that the pageable object i obtained in the slice.nextPageable() was in Sort.UNSORTED mode instead of having the sort of my input pageable.
then, knowing that i made this workaround:
public Slice<Pony> getAllByTypePage(Pageable p, EnumType type) {
Slice<Pony> slice = ponyRepository.findAllByType(p.first(), type);
//using a sidePageable and incrementing it in parallel
Pageable sidePageable = p.first();
//Iterate over slices
while(slice.hasNext()&&sidePageable.getPageNumber()<p.getPageNumber())
{
CassandraPageRequest cpr = CassandraPageRequest.of(sidePageable.next(), ((CassandraPageRequest)slice.getPageable()).getPagingState());
slice = ponyRepository.findAllByType(cpr, type);
sidePageable=sidePageable.next();
}
return slice;
}
the workaround seems to work.
Is this behavior is normal or is it a bug?
i have not seen any issues about this in the jira (maybe i did not looked at the good place).
here is the related libs i use (spring boot 2.2.1/spring code 5.2.1):
spring-data-cassandra : 2.2.1.RELEASE
cassandra-driver-core: 3.7.2
i have seen the same behavior on spring core 5.1.5
Best Regards
like said in the previous comments, it was a bug.
this is already fixed (see the issue linked before).
I just tried with the snapshot 2.2.2.BUILD-20191113.121102-4 and it seems to work.
for now i'll use my workaround. When the lib will be released i'll upgrade.
thanks for the help #mp911de
Currently when using OrmLite library from ServiceStack if I want single entity selected I do:
AppUser user = db.First<AppUser>(q => q.Id == id);
However since Single is more precise (obviously I want exception thrown if somehow multiple users with same id ended up in database) I was wondering if there is overload that I can use. Currently when I do db.Single I just get that overload with manual filtering:
public static T SingleOrDefault<T>(this IDbConnection dbConn, string filter);
OK, I found what the issue is - the version I'm using (3.9.71) doesn't have that overload - it was added later:
https://github.com/ServiceStack/ServiceStack.OrmLite/commit/f2f5f80f150f27266bdcaf81b77ca60b62897719#diff-e9a84724e6a8315ec7f7fc5a5512a44b
Seems I'll need to extend that class from within my code.
I have basically the same question as the one I asked here. Adding the using Xceed.Wpf.Toolkit.PropertyGrid.Attributes directive solved that.
This time, the compiler does not like [Category("Shipping")] decoration.
[Category("Shipping")]
public string ShipAddress { get; set; }
How can I deduce or determine what namespace needs to be included when I run into obstacles like this?
Here are the using directives I've included already:
using Xceed.Wpf.Toolkit.PropertyGrid;
using Xceed.Wpf.Toolkit.PropertyGrid.Editors;
using Xceed.Wpf.Toolkit.PropertyGrid.Commands;
using Xceed.Wpf.Toolkit.PropertyGrid.Converters;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
The xaml is this:
<xctk:PropertyGrid AutoGenerateProperties="True" Name="XPG1" IsCategorized="True" />
I know this is an older question, but since it's unanswered I thought it would be helpful to provide one anyway. In this case you need the following using statement:
using System.ComponentModel;
In general, the best way to figure out what namespace or using statement you need is to look for the name of the attribute in the Object Browser under the Xceed namespace, and if you can't find it there, on Google.
One thing to remember - while it shows up as just [Category] in code, the actual name of the class will be CategoryAttribute.
I've taken a read to the Advantages of message based web services article and am wondering if there is there a recommended style/practice to versioning Restful resources in ServiceStack? The different versions could render different responses or have different input parameters in the Request DTO.
I'm leaning toward a URL type versioning (i.e /v1/movies/{Id}), but I have seen other practices that set the version in the HTTP headers (i.e Content-Type: application/vnd.company.myapp-v2).
I'm hoping a way that works with the metadata page but not so much a requirement as I've noticed simply using folder structure/ namespacing works fine when rendering routes.
For example (this doesn't render right in the metadata page but performs properly if you know the direct route/url)
/v1/movies/{id}
/v1.1/movies/{id}
Code
namespace Samples.Movies.Operations.v1_1
{
[Route("/v1.1/Movies", "GET")]
public class Movies
{
...
}
}
namespace Samples.Movies.Operations.v1
{
[Route("/v1/Movies", "GET")]
public class Movies
{
...
}
}
and corresponding services...
public class MovieService: ServiceBase<Samples.Movies.Operations.v1.Movies>
{
protected override object Run(Samples.Movies.Operations.v1.Movies request)
{
...
}
}
public class MovieService: ServiceBase<Samples.Movies.Operations.v1_1.Movies>
{
protected override object Run(Samples.Movies.Operations.v1_1.Movies request)
{
...
}
}
Try to evolve (not re-implement) existing services
For versioning, you are going to be in for a world of hurt if you try to maintain different static types for different version endpoints. We initially started down this route but as soon as you start to support your first version the development effort to maintain multiple versions of the same service explodes as you will need to either maintain manual mapping of different types which easily leaks out into having to maintain multiple parallel implementations, each coupled to a different versions type - a massive violation of DRY. This is less of an issue for dynamic languages where the same models can easily be re-used by different versions.
Take advantage of built-in versioning in serializers
My recommendation is not to explicitly version but take advantage of the versioning capabilities inside the serialization formats.
E.g: you generally don't need to worry about versioning with JSON clients as the versioning capabilities of the JSON and JSV Serializers are much more resilient.
Enhance your existing services defensively
With XML and DataContract's you can freely add and remove fields without making a breaking change. If you add IExtensibleDataObject to your response DTO's you also have a potential to access data that's not defined on the DTO. My approach to versioning is to program defensively so not to introduce a breaking change, you can verify this is the case with Integration tests using old DTOs. Here are some tips I follow:
Never change the type of an existing property - If you need it to be a different type add another property and use the old/existing one to determine the version
Program defensively realize what properties don't exist with older clients so don't make them mandatory.
Keep a single global namespace (only relevant for XML/SOAP endpoints)
I do this by using the [assembly] attribute in the AssemblyInfo.cs of each of your DTO projects:
[assembly: ContractNamespace("http://schemas.servicestack.net/types",
ClrNamespace = "MyServiceModel.DtoTypes")]
The assembly attribute saves you from manually specifying explicit namespaces on each DTO, i.e:
namespace MyServiceModel.DtoTypes {
[DataContract(Namespace="http://schemas.servicestack.net/types")]
public class Foo { .. }
}
If you want to use a different XML namespace than the default above you need to register it with:
SetConfig(new EndpointHostConfig {
WsdlServiceNamespace = "http://schemas.my.org/types"
});
Embedding Versioning in DTOs
Most of the time, if you program defensively and evolve your services gracefully you wont need to know exactly what version a specific client is using as you can infer it from the data that is populated. But in the rare cases your services needs to tweak the behavior based on the specific version of the client, you can embed version information in your DTOs.
With the first release of your DTOs you publish, you can happily create them without any thought of versioning.
class Foo {
string Name;
}
But maybe for some reason the Form/UI was changed and you no longer wanted the Client to use the ambiguous Name variable and you also wanted to track the specific version the client was using:
class Foo {
Foo() {
Version = 1;
}
int Version;
string Name;
string DisplayName;
int Age;
}
Later it was discussed in a Team meeting, DisplayName wasn't good enough and you should split them out into different fields:
class Foo {
Foo() {
Version = 2;
}
int Version;
string Name;
string DisplayName;
string FirstName;
string LastName;
DateTime? DateOfBirth;
}
So the current state is that you have 3 different client versions out, with existing calls that look like:
v1 Release:
client.Post(new Foo { Name = "Foo Bar" });
v2 Release:
client.Post(new Foo { Name="Bar", DisplayName="Foo Bar", Age=18 });
v3 Release:
client.Post(new Foo { FirstName = "Foo", LastName = "Bar",
DateOfBirth = new DateTime(1994, 01, 01) });
You can continue to handle these different versions in the same implementation (which will be using the latest v3 version of the DTOs) e.g:
class FooService : Service {
public object Post(Foo request) {
//v1:
request.Version == 0
request.Name == "Foo"
request.DisplayName == null
request.Age = 0
request.DateOfBirth = null
//v2:
request.Version == 2
request.Name == null
request.DisplayName == "Foo Bar"
request.Age = 18
request.DateOfBirth = null
//v3:
request.Version == 3
request.Name == null
request.DisplayName == null
request.FirstName == "Foo"
request.LastName == "Bar"
request.Age = 0
request.DateOfBirth = new DateTime(1994, 01, 01)
}
}
Framing the Problem
The API is the part of your system that exposes its expression. It defines the concepts and the semantics of communicating in your domain. The problem comes when you want to change what can be expressed or how it can be expressed.
There can be differences in both the method of expression and what is being expressed. The first problem tends to be differences in tokens (first and last name instead of name). The second problem is expressing different things (the ability to rename oneself).
A long-term versioning solution will need to solve both of these challenges.
Evolving an API
Evolving a service by changing the resource types is a type of implicit versioning. It uses the construction of the object to determine behavior. Its works best when there are only minor changes to the method of expression (like the names). It does not work well for more complex changes to the method of expression or changes to the change of expressiveness. Code tends to be scatter throughout.
Specific Versioning
When changes become more complex it is important to keep the logic for each version separate. Even in mythz example, he segregated the code for each version. However, the code is still mixed together in the same methods. It is very easy for code for the different versions to start collapsing on each other and it is likely to spread out. Getting rid of support for a previous version can be difficult.
Additionally, you will need to keep your old code in sync to any changes in its dependencies. If a database changes, the code supporting the old model will also need to change.
A Better Way
The best way I've found is to tackle the expression problem directly. Each time a new version of the API is released, it will be implemented on top of the new layer. This is generally easy because changes are small.
It really shines in two ways: first all the code to handle the mapping is in one spot so it is easy to understand or remove later and second it doesn't require maintenance as new APIs are developed (the Russian doll model).
The problem is when the new API is less expressive than the old API. This is a problem that will need to be solved no matter what the solution is for keeping the old version around. It just becomes clear that there is a problem and what the solution for that problem is.
The example from mythz's example in this style is:
namespace APIv3 {
class FooService : RestServiceBase<Foo> {
public object OnPost(Foo request) {
var data = repository.getData()
request.FirstName == data.firstName
request.LastName == data.lastName
request.DateOfBirth = data.dateOfBirth
}
}
}
namespace APIv2 {
class FooService : RestServiceBase<Foo> {
public object OnPost(Foo request) {
var v3Request = APIv3.FooService.OnPost(request)
request.DisplayName == v3Request.FirstName + " " + v3Request.LastName
request.Age = (new DateTime() - v3Request.DateOfBirth).years
}
}
}
namespace APIv1 {
class FooService : RestServiceBase<Foo> {
public object OnPost(Foo request) {
var v2Request = APIv2.FooService.OnPost(request)
request.Name == v2Request.DisplayName
}
}
}
Each exposed object is clear. The same mapping code still needs to be written in both styles, but in the separated style, only the mapping relevant to a type needs to be written. There is no need to explicitly map code that doesn't apply (which is just another potential source of error). The dependency of previous APIs is static when you add future APIs or change the dependency of the API layer. For example, if the data source changes then only the most recent API (version 3) needs to change in this style. In the combined style, you would need to code the changes for each of the APIs supported.
One concern in the comments was the addition of types to the code base. This is not a problem because these types are exposed externally. Providing the types explicitly in the code base makes them easy to discover and isolate in testing. It is much better for maintainability to be clear. Another benefit is that this method does not produce additional logic, but only adds additional types.
I am also trying to come with a solution for this and was thinking of doing something like the below. (Based on a lot of Googlling and StackOverflow querying so this is built on the shoulders of many others.)
First up, I don’t want to debate if the version should be in the URI or Request Header. There are pros/cons for both approaches so I think each of us need to use what meets our requirements best.
This is about how to design/architecture the Java Message Objects and the Resource Implementation classes.
So let’s get to it.
I would approach this in two steps. Minor Changes (e.g. 1.0 to 1.1) and Major Changes (e.g 1.1 to 2.0)
Approach for minor changes
So let’s say we go by the same example classes used by #mythz
Initially we have
class Foo { string Name; }
We provide access to this resource as /V1.0/fooresource/{id}
In my use case, I use JAX-RS,
#Path("/{versionid}/fooresource")
public class FooResource {
#GET
#Path( "/{id}" )
public Foo getFoo (#PathParam("versionid") String versionid, (#PathParam("id") String fooId)
{
Foo foo = new Foo();
//setters, load data from persistence, handle business logic etc
Return foo;
}
}
Now let’s say we add 2 additional properties to Foo.
class Foo {
string Name;
string DisplayName;
int Age;
}
What I do at this point is annotate the properties with a #Version annotation
class Foo {
#Version(“V1.0")string Name;
#Version(“V1.1")string DisplayName;
#Version(“V1.1")int Age;
}
Then I have a response filter that will based on the requested version, return back to the user only the properties that match that version. Note that for convenience, if there are properties that should be returned for all versions, then you just don’t annotate it and the filter will return it irrespective of the requested version
This is sort of like a mediation layer. What I have explained is a simplistic version and it can get very complicated but hope you get the idea.
Approach for Major Version
Now this can get quite complicated when there is a lot of changes been done from one version to another. That is when we need to move to 2nd option.
Option 2 is essentially to branch off the codebase and then do the changes on that code base and host both versions on different contexts. At this point we might have to refactor the code base a bit to remove version mediation complexity introduced in Approach one (i.e. make the code cleaner) This might mainly be in the filters.
Note that this is just want I am thinking and haven’t implemented it as yet and wonder if this is a good idea.
Also I was wondering if there are good mediation engines/ESB’s that could do this type of transformation without having to use filters but haven’t seen any that is as simple as using a filter. Maybe I haven’t searched enough.
Interested in knowing thoughts of others and if this solution will address the original question.
I have a custom type converter that converts UTC DateTime properties to a company's local time (talked about here: Globally apply value resolver with AutoMapper).
I'd now like to only have this converter do its thing if the property on the view model is tagged with a custom DisplayInLocalTime attribute.
Inside the type converter, if I implement the raw ITypeConvert<TSource, TDestination> interface, I can check if the destination view model property being converted has the attribute:
public class LocalizedDateTimeConverter : ITypeConverter<DateTime, DateTime>
{
public DateTime Convert(ResolutionContext context)
{
var shouldConvert = context.Parent.DestinationType
.GetProperty(context.MemberName)
.GetCustomAttributes(false)[0].GetType() == typeof(DisplayInLocalTimeAttribute);
if (shouldConvert) {
// rest of the conversion logic...
}
}
}
So this code works just fine (obviously there's more error checking and variables in there for readability).
My questions:
Is this the correct way to go about this? I haven't found anything Googling around or spelunking through the AutoMapper code base.
How would I unit test this? I can set the parent destination type on the ResolutionContext being passed in with a bit of funkiness, but can't set the member name as all implementors of IMemberAccessor are internal to AutoMapper. This, and the fact that it's super ugly to setup, makes me this isn't really supported or I'm going about it all wrong.
I'm using the latest TeamCity build of AutoMapper, BTW.
Don't unit test this, use an integration test. Just write a mapping test that actually calls AutoMapper, verifying that whatever use case this type converter is there to support works from the outside.
As a general rule, unit tests on extension points of someone else's API don't have as much value to me. Instead, I try to go through the front door and make sure that I've configured the extension point correctly as well.