ASP.NET MVC 2 validation of Date using DataAnnotations not working - asp.net-mvc-2

I am using the following in my model for a date control
[DataType(DataType.DateTime)]
public DateTime txtDateAppCompletion { get; set; }
I also tried DataType.Date as I only want a date input.
[DataType(DataType.Date)]
public DateTime txtDateAppCompletion { get; set; }
For some reason when I run the form and I type anything that is not a date it does not validate it, not on server or on client(client validation is enabled).
Any Idea why I am having this problems? How to solve it?

Ok, after some research I found this in a Microsoft book.
■ Caution Even though [DataType] looks
like a validation attribute along with
the others in Data Annotations,
ASP.NET MVC does not treat it as one,
so don’t expect
[DataType(DataType.EmailAddress)] to
validate for legal e-mail addresses!
[DataType] is an anomaly; even though
it inherits from
System.ComponentModel.DataAnnotations.ValidationAttribute,
its IsValid() method is hard-coded to
return true regardless of the
property’s value. Microsoft has
explained that [DataType] is only
meant to serve as a hint for
formatting data in a scaffolded UI...

Related

ServiceStack REST API Versioning practical questions

Our team is looking for a convenient way to implement versioning in our ServiceStack API implementation.
I've read the articles:
ServiceStack: RESTful Resource Versioning
https://docs.servicestack.net/versioning#implicit-versioning
ServiceStack versioning - how to customize the request deserialization based on versioning
But I don't get a practical way of working for our system.
I've made a list of changes that could happen in the lifetime of the application:
No breaking changes:
Add a new service
Add a new property to an existing request DTO
Add a new property to an existing response DTO
Add a response to an existing (void) request DTO
Breaking changes:
Remove a service. This breaks the client if the service will be called.
Remove a property of an existing request DTO. May not break, but it will be ignored in
the service, thus the response may differ.
Remove a property of an existing response DTO. This breaks if the calling client uses the property.
Remove HTTP verbs. Replace Any with the desired GET, POST, PUT, DELETE, etc. verbs.
Different semantic meanings of service. Same request name, but different behaviour.
Combinations of breaking changes:
Renaming a service. Thus adding a new service and removing the old one.
Rename a property of an existing request DTO.
Rename a property of an existing response DTO.
Split up property of an existing request DTO.
Split up property of an existing response DTO.
We deliver a new release twice a year. Our naming scheme is very simple and looks like:
2020.1.0
2020.2.0
2021.1.0
2021.2.0
xxxx.x.0
We have service packs within the releases. Service packs cannot contain database changes and breaking API changes. The naming scheme is simple:
2020.1.1
2020.1.2
2020.1.3
2020.1.x
2021.1.1
2021.1.2
2021.1.x
Our client and server apps are delivered at the same time on a customer site. Thus with our software delivery, we update all the software at once. No problems so far.
The problem we have has to do with partners and customers who are using the API and may face breaking changes.
We do not want a partner or customer to force their software simultaneously when we update our software at the customer site. There should be some grace period where the partner or customer can update their clients of our API.
We have the following idea:
Partner en customer client develops against a specific version of our API by giving the release version number. I.e. 20201 (=2020.1) in the header, url or querystring parameter (which is best/supported?).
ServiceStack in our implementation should notice the version specified by the client and let it discovers only the available APIs which belong to that version. Thus if our software is version 2021.2, then it should 'downgrade' its API exploration to the specified version. The idea is that every request DTO and response DTO has a version property with a similar versioning strategy as with aspnet-api-versioning (https://github.com/dotnet/aspnet-api-versioning/wiki).
I've tried to experiment with the current capabilities of ServiceStack in the following example.
// ServiceStack configuration in AppHost
public override void Configure(Funq.Container container)
{
SetConfig(new HostConfig
{
ApiVersion = "20231"
});
var nativeTypes = GetPlugin<NativeTypesFeature>();
nativeTypes.MetadataTypesConfig.AddImplicitVersion = 20231;
}
public class Project
{
public int ID { get; set; }
public Guid GlobalID { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public string Description1 { get; set; }
public string Description2 { get; set; }
public string City { get; set; }
public bool Active { get; set; }
}
[Route("/projects", "GET POST")]
public class GetProjects : IReturn<List<Project>>
{
public string SearchCriteria { get; set; }
public int PageSize { get; set; } = Constants.DefaultPageSize;
public int PageNumber { get; set; } = Constants.DefaultPageNumber;
public string OrderBy { get; set; }
}
public class ProjectV20231
{
public int ID { get; set; }
public Guid GlobalID { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string City { get; set; }
public bool Active { get; set; }
}
public enum OrderByDirection { Asc, Desc }
public class OrderByElement
{
public string Field { get; set; }
public OrderByDirection Direction { get; set; }
}
[Route("/projects", "GET")]
public class GetProjectsV20231 : IReturn<List<ProjectV20231>>
{
public string SearchTerm { get; set; }
public int Offset { get; set; }
public int Limit { get; set; }
public List<OrderByElement> OrderBy { get; set; }
public bool? Active { get; set; } = null;
}
public class ProjectsService : Service
{
public List<Project> Get(GetProjects request)
{
var result = new List<Project>
{
new Project() { Name = "2020.1" }
};
return result;
}
public List<ProjectV20231> Get(GetProjectsV20231 request)
{
var result = new List<ProjectV20231>
{
new ProjectV20231() { Name = "2023.1" }
};
return result;
}
}
We have a lot of existing services without any versioning. In this example that is GetProjects request and Project response. As long as there are no breaking changes we could keep the request and response DTOs without any version specification.
When we have a redesign of our API, we could introduce a new request and/or response DTO with the name extension V[ReleaseAndServicePackVersion], for example, GetProjectsV20231 and List ProjectV20231.
If partners or customers programmed against the 2020.1 version, then this should be set in the ServiceStack client or querystring:
client.Version = 20201;
client.Get(new GetProjects());
/api/projects?v=20201
If partners or customers want to use our new version, then they should update the version number and repair any breaking changes.
client.Version = 20231;
client.Get(new GetProjects());
Note: I still use GetProjects, although this probably won't work because they should use GetProjectsV20231 instead. But why should we specify the Version property of the client than any more?
If they don't use our DTOs, but are using the querystring approach, then the call should look transparent (although it is not, because the response is different).
/api/projects?v=20231
Questions:
Can we let ServiceStack show only the services which correspond to a specified version of the API? For example /api?v=20231 must only show the 2023.1 compatible services.
Is there a more convenient way to solve the versioning for our system? For ASP.NET a lot of research is already done, see https://github.com/dotnet/aspnet-api-versioning/wiki. Could this also be implemented in ServiceStack?
Should we also rename the GetProject request and Project response to GetProjectV20201 and ProjectV20201, otherwise ServiceStack don't know that these request and response are now version specific.
If 2023.2 version is out and there is no breaking change for GetProjects20231 then GetProjectsV20231 should be used, because it is the latest available version for the request. How can we configure/program ServiceStack to do that?
This Sounds like it's looking for a magic bullet to version typed APIs when there really isn't one, existing Typed clients are going to expect their Typed Request and Typed Response to remain the same which means the server needs to forever fulfill that API contract for as long as you want to make legacy versions of the Service available.
Versioning in Dynamic Languages
IMO dynamically routing requests to different based on a ?v=xx query parameter is only really feasible in dynamic languages who are better able to use model transformers to map how existing requests map to newer requests, call the newer API implementation then map their responses back to existing API contracts of existing Services, in ServiceStack it would look something like:
public class MyServices : Service
{
public object Any(GetProject request)
{
var v2Request = request.ConvertTo<GetProjectV2>();
var v2Response = Any(v2Request);
return v2Response.ConvertTo<GetProjectResponse>();
}
public object Any(GetProjectV2 request)
{
//...
return new GetProjectV2Response { ... }
}
}
This would take dramatically less effort to maintain in dynamic languages which can do the transformation with just mappers without introducing new types.
Versioning in Typed APIs
But adding new breaking API versions in typed APIs is going to result in an explosion of new API Request/Response, DTO and Data Model Types that's going to become less and less maintainable the more versions you need to support which is why the recommendation is to evolve your services by enhancing existing Services defensively so existing APIs can handle both old and new Requests.
API Version Info
Populating the Version in Request DTOs is to make it easier for APIs to determine which client version sent the request instead of trying to infer the version based on the heuristics of what parameters were sent with the API Request.
But if you want to make breaking changes with different Request/Response schemas you're going to need to create new Typed APIs. Given the effort to maintain multiple different API versions, making breaking changes should be a last resort. But if I wanted to enable it I'd put the version in the /path/info so it's given a permanent URL that wont change, e.g:
[Route("/v1/projects")]
public class GetProjects {}
[Route("/v2/projects")]
public class GetProjectsV2 {}
I'd disregard applying your external software versioning scheme to APIs (e.g. GetProjectV20231) and just version each API independently, primarily focusing on evolving them with backwards-compatible changes, and only adding new APIs when breaking changes are necessary.
Versioning Code Bases
New software releases could be updated to have the latest version of your APIs maintain the optimal name for the latest API e,g:
[Route("/v1/projects")]
public class GetProjectsV1 {}
[Route("/v2/projects")]
public class GetProjects {}
Newer versions of your software could rename the Server DTOs to their optimal names which should still support existing clients using existing DTOs since their schema contracts remain the same. They'll only need to update their clients when they want to use your software's latest typed API DTOs.
API Grouping
As for grouping your APIs I'd recommend using Tag Groups to group them, which can utilize your software versioning scheme to annotate APIs available in different versions, e.g:
[Tag("v2022.6")]
[Route("/v1/projects")]
public class GetProjectsV1 {}
[Tag("v2023.1")]
[Route("/v2/projects")]
public class GetProjects {}
[Tag("v2022.6"),Tag("v2023.1")]
[Route("/v1/projects/{Id}")]
public class GetProject {}
This will allow clients to browse APIs available in different versions in Metadata Pages as well as the built-in API Explorer.
It's also supported in Add ServiceStack Reference which can be used by clients to only generate DTOs for APIs in different versions.

MVC FoolProof Validation showing exception while calling SaveChange method

This question mayt sound duplicate but I am not satisfied with any of the answers as some are suggesting MVC Foolproof validaiton for conditional validaiton and some tells it dont work well with entity framework
I am using MVC Foolproof RequiredIf validation in my project.It works well on clientside and is validation is working on server side as well.
[RequiredIf("STCompulsory",Operator.EqualTo,true,ErrorMessage="Please enter Registration No")]
public string STRegNo { get; set; }
But when i call db.Savechanges() to insert data an exception is coming
An unexpected exception was thrown during validation of 'STRegNo' when invoking
Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.
InnerException
The method or operation is not implemented.
You do not need the Operator.EqualTo parameter and it can be simply
[RequiredIf("STCompulsory", true, ErrorMessage="Please enter Registration No")
public string STRegNo { get; set; }
You are correct in that the foolproof [RequiredIf] attribute does have some problems with EF and it is discussed in detail in this work issue (along with some suggested changes).
The easiest solution is to use a view model rather than your data model in the view, and apply the attribute to the view model property.

How do I access SOAP headers in a Spyne srpc method?

Forgive me if I am just being thick but the Spyne documentation on headers seems a bit thin and the link to the sample code is broken. I think I found the sample code here but it only seems to access the headers in a listener callback function. I need access to it in the srpc method if possible.
What I would like to do is something like this (this does not work):
class MyRequest(ComplexModel):
Messages = Array(Unicode)
class MyHeader(ComplexModel):
TrackingID = ByteArray
class MySoapService(ServiceBase):
#srpc(MyRequest, _in_header=MyHeader)
def PostMessages(req, hdr):
logging.info(u'RECEIVED: {0:s}'.format(hdr.TrackingID))
If it helps, I am trying to replace a service written in .NET that just defines the message headers in the message contract like this:
[MessageContract]
public class MyRequest
{
[MessageHeader]
public Guid TrackingID { get; set; }
[MessageBodyMember]
public String[] Messages { get; set; }
}
You can't read header data from within an srpc function. #srpc is for existing functions that you don't want to touch. You should always use #rpc unless you know you need #srpc
Decorate your function using #rpc. This passes the rpc context (conventionally named ctx) as first argument to your function. Then, ctx.in_header is where you'll find the header data. You can also set ctx.out_header to alter outgoing response headers.
Also, pull requests for docs are pure gold to me :)

Hyperlinking in WebAPI

Is there any solid guidance for generating hyperlinks for your resources in ASP.NET WebAPI? I've read a couple of posts on this:
http://codebetter.com/glennblock/2012/01/08/hypermedia-and-web-api-design-brain-dump-and-samples/
http://blog.ploeh.dk/2012/04/17/HyperlinkingWithTheASPNETWebAPI.aspx
Although informative, there appears to be no concrete guidance from Microsoft or otherwise in terms of how best to implement links for your resources (i.e. object model implemented using DTOs at the service layer). If we are moving towards using WebAPI to implement a true RESTful service, hyperlinking is crucial and I would have expected built in support / guidance for this in WebAPI.
A simple example I'm trying to implement this for is using a Contact entity which has a collection of Addresses and a collection of SupportIncident.
The class definitions based on the first article I've referenced would look something like so:
public class Link
{
public Uri Uri { get; set; }
public string Rel { get; set; }
public string Name { get; set; }
}
public class ContactDTO
{
public int ID { get; set; }
public string Name { get; set; }
public IList<AddressDTO> Addresses { get; set; }
public IList<IncidentDTO> Incidents{ get; set; }
public IList<Link> Links { get; set; }
}
WebAPI is great at exposing this model over HTTP (xml/json) and the GET/PUT/POST/DELETE action on the resource but in order to build a true RESTful service I would like to know if
a) Is there inherent support for link generation in WEBAPI?
b) Is there proper guidance for exposing the model above containing links to resources and how should the API handle PUT/POST if a client sends links as part of the payload. Should these be ignored?
In my opinion, Ben Foster did a great job on this. See the below blog post:
Generating Hypermedia links in ASP.NET Web API
The basic idea is that you will modify the ObjectContent's Value property on the way out through a message handler. This message handler delegates this work onto registered so-called "Response Enrichers" and each one of them has a chance to evaluate to see whether it can enrich the object type or not.
I built a sample application that demonstrates the use of Hypermedia in Web API here. There is another one here https://github.com/webapibook/issuetracker and Amy Palamountain has another good example here https://github.com/ammeep/hyper-library.
One of the main problems with using DTOs and links is that by default these DTOs will be serialized out as application/json or application/xml. Neither of those media types have any specifications for how links should be serialized. Therefore a client requires out-of-band knowledge on how to process those links.
To do hypermedia properly, you need to be using a hypermedia enabled media type, like xhtml, hal, collection+json, json-ld, siren.

Response and DTO objects missing from XSD

I'm using the latest version of ServiceStack with NuGet. I've got a basic service setup that works fine with the JsonServiceClient and is passing all of our unit tests as expected.
Unfortunately I'm also trying to support SOAP and Visual Studios "Add Service Refernece" proxy generation for interop with other groups who want to continue using that sort of framework.
What I'm running into is that our DTO's including the Response objects are not being populated into the XSD's or wsdl's that ServiceStack is generating via the metadata page. This seems very odd in conjunction with the fact that when viewing the individual SOAP Operation examples the correct Response and DTO's are shown in the generated example.
An Example Response:
Namespace Operations
<DataContract>
Public Class GetItemResponse
Implements IHasResponseStatus
<DataMember>
Public Property ResponseStatus As ResponseStatus Implements IHasResponseStatus.ResponseStatus
<DataMember>
Public Property Item As Item
End Class
End Namespace
An Example DTO:
Namespace Types
<DataContract>
Public Class Item
<DataMember>
Public Property ItemIdentifier As String
<DataMember>
Public Property ItemId As Guid?
<DataMember>
Public Property ItemName As String
<DataMember>
Public Property Description As String
<DataMember>
Public Property InstallDate As DateTime?
<DataMember>
Public Property FeatureNumber As String
<DataMember>
Public Property ModelNumber As String
End Class
End Namespace
I'm using the Assembly: ContractNamespace attribute to set the XML namespace as well.
I've downloaded the source code and done some investigation on my own. I'm not sure how recent this change is but it appears that in order for your DTO's and Response objects to be included in the wsdl you need to add a query string like "?includeAllTypes=true".
I'm also using the ServiceStack BasicAuthProvider setup which is causing AssignRoles and UnAssignRoles to be added to the Service automatically. The request and response objects for those calls are still failing to make it into the wsdl and causing "Add Service Reference" to fail. Fortunately we aren't making use of them so if I can find another configuration setting to remove them all should be working correctly.