Web API Model binding - Complex Parameter - rest

I have a string received in query string
f[0][p]=zap&f[0][v][] = 110&f[0][v][]=500&f[1][p] = prih&f[1][v][] = 10000000&f[1][v][] = 30000000000
I try to catch it with string[] but it is always null. How to represent this parameter to Web API so it can serialize it?
I have a workaround with reading it for Uri as a string and then parse it but it is not good for unit testing and would like to update it.
Is it even possible with structure like this?

Ok, I solved this, maybe it can help someone.
I needed a class to represent the received object :
public class Filter
{
private string p { get; set; }
private string[] v { get; set; }
private string cp { get; set; }
private string[] cv { get; set; }
}
And in method definition I needed:
public SubjectStats BusinessSubjects(string country, string start, string end, [FromUri] Filter[] f)
The key was to define object as Filter[] in method signature.

Related

Handling Dates with OData v4, EF6 and Web API v2.2

I'm in the midst of upgrading from v1-3 to v4, but I've run into a few problems.
My understanding is that DateTime is unsupported, and I have to always use DateTimeOffset. Fine.
But before I was storing Sql date data type in the DateTime, now it seems I get this error:
Member Mapping specified is not valid. The type 'Edm.DateTimeOffset[Nullable=False,DefaultValue=,Precision=]' of member 'CreatedDate' in type 'MyEntity' is not compatible with 'SqlServer.date[Nullable=False,DefaultValue=,Precision=0]'
What is the work around for this? I need to be able to store specifically just dates in the database (time and locality is not important). Would be great if I could get the Edm.Date aswell as a returned data type, but I didn't have that before.
Thanks.
Edit: Example classes
Before:
public class Ticket
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required, MaxLength(50)]
public string Reference { get; set; }
[Column(TypeName = "date")]
public DateTime LoggedDate { get; set; }
}
After:
public class Ticket
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required, MaxLength(50)]
public string Reference { get; set; }
[Column(TypeName = "date")]
public DateTimeOffset LoggedDate { get; set; }
}
This isn't valid in EF.
One option is to define a new property in the entity. Say Title is mapped to EF:
public partial class Title
{
public int Id { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
}
then add a new property of DateTimeOffset:
public partial class Title
{
[NotMapped]
public DateTimeOffset? EdmCreatedOn
{
// Assume the CreateOn property stores UTC time.
get
{
return CreatedOn.HasValue ? new DateTimeOffset(CreatedOn.Value, TimeSpan.FromHours(0)) : (DateTimeOffset?)null;
}
set
{
CreatedOn = value.HasValue ? value.Value.UtcDateTime : (DateTime?)null;
}
}
}
and the code for generate OData Model looks like:
public static IEdmModel GetModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
EntityTypeConfiguration<Title> titleType= builder.EntityType<Title>();
titleType.Ignore(t => t.CreatedOn);
titleType.Property(t => t.EdmCreatedOn).Name = "CreatedOn";
builder.EntitySet<Title>("Titles");
builder.Namespace = typeof(Title).Namespace;
return builder.GetEdmModel();
}
}
The controller looks like:
public class TitlesController : ODataController
{
CustomerManagementSystemEntities entities = new CustomerManagementSystemEntities();
[EnableQuery(PageSize = 10, MaxExpansionDepth = 5)]
public IHttpActionResult Get()
{
IQueryable<Title> titles = entities.Titles;
return Ok(titles);
}
public IHttpActionResult Post(Title title)
{
entities.Titles.Add(title);
return Created(title);
}
}
For anyone coming to this in the future, the OData v4 team have fixed this issue.
[Column(TypeName = "date")]
public DateTime Birthday { get; set; }
This will now auto-resolve to Edm.Date.
If you are like me and are doing date type by convention, you have to manually declare the properties as dates lest they be auto-resolved as DateTimeOffset. OData currently does not allow you to add your own conventions.
customer.Property(c => c.Birthday).AsDate();
http://odata.github.io/WebApi/#12-01-DateAndTimeOfDayWithEF
You can refer to the link below to define your DateTimeAndDateTimeOffsetWrapper to do the translation between two types.
http://www.odata.org/blog/how-to-use-sql-spatial-data-with-wcf-odata-spatial/
Define two properties on your model, one is DateTime which only exists in the Edm model, the other is DateTimeOffset which only exists in the DB.
If the solution above doesn't meet your request, you have to change the data to DateTime before saving it to database and change it back to DateTimeOffset after retrieving it from database in the controller actions.
You can define two almost-same classes to achieve this. The only difference is that one has DateTime property and the other has DateTimeOffset property.
The former one is used for EF and mapping into DB.
The latter one is used for defining OData Edm model and presenting to the users.
As I said above, you have to do the translation between these two classes before saving the data and after retrieving the data.
You can add the AppendDatetimeOffset method to add automatically the methods
using the microsoft T4 engine (i.e. updating the template file *.tt). So that when regenerating the code, you don't have to append classes again. Hope this Helps :)
public string Property(EdmProperty edmProperty)
{
return string.Format(
CultureInfo.InvariantCulture,
(_ef.IsKey(edmProperty) ? "[Key]" : "") +
"{0} {1} {2} {{ {3}get; {4}set; }} {5}",
Accessibility.ForProperty(edmProperty),
_typeMapper.GetTypeName(edmProperty.TypeUsage),
_code.Escape(edmProperty),
_code.SpaceAfter(Accessibility.ForGetter(edmProperty)),
_code.SpaceAfter(Accessibility.ForSetter(edmProperty)),
AppendDateTimeOffset(edmProperty));
}
public string AppendDateTimeOffset(EdmProperty edmProperty){
if(!_typeMapper.GetTypeName(edmProperty.TypeUsage).Contains("DateTime")) return " ";
//proceed only if date time
String paramNull = #"public Nullable<System.DateTimeOffset> edm{0}
{{
get
{{
return {0}.HasValue ? new DateTimeOffset({0}.Value, TimeSpan.FromHours(0)) : (DateTimeOffset?)null;
}}
}}";
String paramNotNull = #"public System.DateTimeOffset edm{0}
{{
get
{{
return new DateTimeOffset({0}, TimeSpan.FromHours(0));
}}
}}";
String s= String.Empty;
if(edmProperty.Nullable){
s = string.Format(paramNull, edmProperty.Name);
}else
{
s = string.Format(paramNotNull, edmProperty.Name);
}
return s;
}

ServiceStack rest with null?

I'd like to make R a nullable int (and b a nullable bool). I can hit /api/test/1/2 no problem but /api/test/null/2 causes SerializationException
KeyValueDataContractDeserializer: Error converting to type: Input string was not in a correct format
I tried doing /api/test//2 but it ignored the double slash and thought it was {Ids}.
How do I make R nullable?
[Route("/Test")]
[Route("/Test/{Ids}")]
[Route("/Test/{R}/{E}")]
[Route("/Test/a/{Ids}/{R}/{E}/{b}/{f}")]
public class Test
{
public long[] Ids { get; set; }
public int? R{get;set;}
public int E{get;set;}
public bool? b { get; set; }
public float f { get; set; }
}
public class TestService : Service
{
public object Get(Test a)
{
return JsonSerializer.SerializeToString(a);
}
}
The null in your route is treated like a string literal which obviously is not a valid number. Basically you want to avoid passing in null in the first place (i.e. avoid specifying it), e.g instead of:
/api/test/null/2
You can do:
/api/test?E=2

Improve navigation property names when reverse engineering a database

I'm using Entity Framework 5 with Visual Studio with Entity Framework Power Tools Beta 2 to reverse engineer moderately sized databases (~100 tables).
Unfortunately, the navigation properties do not have meaningful names. For example, if there are two tables:
CREATE TABLE Contacts (
ContactID INT IDENTITY (1, 1) NOT NULL,
...
CONSTRAINT PK_Contacts PRIMARY KEY CLUSTERED (ContactID ASC)
}
CREATE TABLE Projects (
ProjectID INT IDENTITY (1, 1) NOT NULL,
TechnicalContactID INT NOT NULL,
SalesContactID INT NOT NULL,
...
CONSTRAINT PK_Projects PRIMARY KEY CLUSTERED (ProjectID ASC),
CONSTRAINT FK_Projects_TechnicalContact FOREIGN KEY (TechnicalContactID)
REFERENCES Contacts (ContactID),
CONSTRAINT FK_Projects_SalesContact FOREIGN KEY (SalesContactID)
REFERENCES Contacts (ContactID),
...
}
This will generate classes like this:
public class Contact
{
public Contact()
{
this.Projects = new List<Project>();
this.Projects1 = new List<Project>();
}
public int ContactID { get; set; }
// ...
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<Project> Projects1 { get; set; }
}
public class Project
{
public Project()
{
}
public int ProjectID { get; set; }
public int TechnicalContactID { get; set; }
public int SalesContactID { get; set; }
// ...
public virtual Contact Contact { get; set; }
public virtual Contact Contact1 { get; set; }
}
I see several variants which would all be better than this:
Use the name of the foreign key: For example, everything after the last underscore (FK_Projects_TechnicalContact --> TechnicalContact). Though this probably would be the solution with the most control, this may be more difficult to integrate with the existing templates.
Use the property name corresponding to the foreign key column: Strip off the suffix ID (TechnicalContactID --> TechnicalContact)
Use the concatenation of property name and the existing solution: Example TechnicalContactIDProjects (collection) and TechnicalContactIDContact
Luckily, it is possible to modify the templates by including them in the project.
The modifications would have to be made to Entity.tt and Mapping.tt. I find it difficult due to the lack of intellisense and debug possibilities to make those changes.
Concatenating property names (third in above list) is probably the easiest solution to implement.
How to change the creation of navigational properties in Entity.tt and Mapping.tt to achieve the following result:
public class Contact
{
public Contact()
{
this.TechnicalContactIDProjects = new List<Project>();
this.SalesContactIDProjects = new List<Project>();
}
public int ContactID { get; set; }
// ...
public virtual ICollection<Project> TechnicalContactIDProjects { get; set; }
public virtual ICollection<Project> SalesContactIDProjects { get; set; }
}
public class Project
{
public Project()
{
}
public int ProjectID { get; set; }
public int TechnicalContactID { get; set; }
public int SalesContactID { get; set; }
// ...
public virtual Contact TechnicalContactIDContact { get; set; }
public virtual Contact SalesContactIDContact { get; set; }
}
There a few things you need to change inside the .tt file. I choose to use the third solution you suggested but this requires to be formatted like FK_CollectionName_RelationName. I split them up with '_' and use the last string in the array.
I use the RelationName with the ToEndMember property to create a property name. FK_Projects_TechnicalContact will result in
//Plularized because of EF.
public virtual Contacts TechnicalContactContacts { get; set; }
and your projects will be like this.
public virtual ICollection<Projects> SalesContactProjects { get; set; }
public virtual ICollection<Projects> TechnicalContactProjects { get; set; }
Now the code you may ask. Ive added 2 functions to the CodeStringGenerator class in the T4 file. One which builds the propertyName recieving a NavigationProperty. and the other one generating the code for the property recieving a NavigationProperty and the name for the property.
//CodeStringGenerator class
public string GetPropertyNameForNavigationProperty(NavigationProperty navigationProperty)
{
var ForeignKeyName = navigationProperty.RelationshipType.Name.Split('_');
var propertyName = ForeignKeyName[ForeignKeyName.Length-1] + navigationProperty.ToEndMember.Name;
return propertyName;
}
public string NavigationProperty(NavigationProperty navigationProperty, string name)
{
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
name,
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}
If you place the above code in the class you still need to change 2 parts. You need to find the place where the constructor part and the navigation property part are being build up of the entity. In the constructor part (around line 60) you need to replace the existing code by calling the method GetPropertyNameForNavigationProperty and passing this into the escape method.
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty);
#>
this.<#=code.Escape(propName)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
<#
And in the NavigationProperties part (around line 100) you also need to replace the code with the following.
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty);
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty, propName)#>
<#
I hope this helps and you can always debug the GetPropertyNameForNavigationProperty function and play a little with the naming of the property.
Building on BikeMrown's answer, we can add Intellisense to the properties using the RelationshipName that is set in MSSQL:
Edit model.tt in your VS Project, and change this:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
}
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
}
}
to this:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
<#
}
#>
/// <summary>
/// RelationshipName: <#=code.Escape(navigationProperty.RelationshipType.Name)#>
/// </summary>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
}
}
Now when you start typing a property name, you get a tooltip like this:
It's probably worth noting that if you change your DB model, the properties may find themselves pointing at different DB fields because the EF generates navigation property names based on their respective DB field name's alphabetic precedence!
Found this question/answer very helpful. However, I didn't want to do as much as Rikko's answer. I just needed to find the column name involved in the NavigationProperty and wasn't seeing how to get that in any of the samples (at least not without an edmx to pull from).
<#
var association = (AssociationType)navProperty.RelationshipType;
#> // <#= association.ReferentialConstraints.Single().ToProperties.Single().Name #>
The selected answer is awesome and got me going in the right direction for sure. But my big problem with it is that it took all of my already working navigation properties and appended the base type name to them, so you'd end up with with things like the following.
public virtual Need UnitNeed { get; set;}
public virtual ShiftEntered UnitShiftEntered {get; set;}`
So I dug into the proposed additions to the .tt file and modified them a bit to remove duplicate type naming and clean things up a bit. I figure there's gotta be someone else out there that would want the same thing so I figured I'd post my resolution here.
Here's the code to update within the public class CodeStringGenerator
public string GetPropertyNameForNavigationProperty(NavigationProperty navigationProperty, string entityname = "")
{
var ForeignKeyName = navigationProperty.RelationshipType.Name.Split('_');
var propertyName = "";
if (ForeignKeyName[ForeignKeyName.Length-1] != entityname){
var prepender = (ForeignKeyName[ForeignKeyName.Length-1].EndsWith(entityname)) ? ReplaceLastOccurrence(ForeignKeyName[ForeignKeyName.Length-1], entityname, "") : ForeignKeyName[ForeignKeyName.Length-1];
propertyName = prepender + navigationProperty.ToEndMember.Name;
}
else {
propertyName = navigationProperty.ToEndMember.Name;
}
return propertyName;
}
public string NavigationProperty(NavigationProperty navigationProperty, string name)
{
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
var truname = name;
if(navigationProperty.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many){
if(name.Split(endType.ToArray<char>()).Length > 1){
truname = ReplaceLastOccurrence(name, endType, "");
}
}
return string.Format(
CultureInfo.InvariantCulture,
"{0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
truname,
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)));
}
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
{
int place = Source.LastIndexOf(Find);
if(place == -1)
return Source;
string result = Source.Remove(place, Find.Length).Insert(place, Replace);
return result;
}
and here's the code to update within the model generation,
update both occurrences of this:
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty)
to this
var propName = codeStringGenerator.GetPropertyNameForNavigationProperty(navigationProperty, entity.Name);

Searching the Entity Framework domain model utilising Code First

Got a very difficult EntityFramework Code First question. I'll keep this as simple as possible.
Imagine we have n number of classes, lets start with 2 for now
public class Person
{
public string Name { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
}
Now then, what I want to do is be able to search the domain model with a single string, i.e. something like DbContext.Search( "Foo" ). The call would search both the person and address tables for a string match and would return a list populated with both Person and Address entities.
Have to say I am not entirely clear how to go about it but I am considering using DataAnnotations to do something like this
public class Person
{
**[Searchable]**
public string Name { get; set; }
}
public class Address
{
**[Searchable]**
public string AddressLine1 { get; set; }
**[Searchable]**
public string AddressLine2 { get; set; }
}
Am I on the right track?
Should I use the Fluent API instead?
Reflection?
Any and all thoughts massively appreciated.
the Find method searches only in the Primary Key column. If we don't make any column explicitly primary key column then find method will throw error. Generally EF convention takes propertyName+id as the primary key in the class. But if you want to search with Name then Make add [Key] to the property. it will become primary key and u will be able to find properties.
dbContext.Addresses.find("Foo");
Create a new object type onto which you'll project 2 types of search results:
public class Result
{
public string MainField { get; set; }
// you may have other properties in here.
}
Then find entities of each type that match your criteria, projecting them onto this type:
var personResults = DbContext.Persons
.Where(p => p.Name == "Foo")
.Select(p => new Result{MainField = p.Name});
// don't forget to map to any other properties you have in Result as well
var addressResults = DbContext.Adresses
.Where(a =>
a.AddressLine1 == "Foo" ||
a.AddressLine2 == "Foo"
).
.Select(a => new Result{MainField = a.AddressLine1 + ", " + a.AddressLine2 });
// again, don't forget to map to any other properties in Result
Then merge the lists:
var allResults = personResults.Union(addressResults).ToList();
...at which point you can sort the list however you like.
"Result" and "MainField", are rather generic; just using them because I am not thoroughly aware of your domain model.

Validation using DataAnnotations Multiple languages

i am writing object with Model validation.
My application is supposed to work with 3 languages( english, german and czech)
How should i assign and after get appropriate language string for validation model?
czech option:
[DisplayName("Nazev")]
[StringLength(200,ErrorMessage="Nazev musi byt 10 az 200 znaku dlouhy",MinimumLength=10)]
[Column]
public string Name { get; set; }
English option:
[DisplayName("Name")]
[StringLength(200,ErrorMessage="Name has to be between 10 and 200",MinimumLength=10)]
[Column]
public string Name { get; set; }
You have to use LocalilizedDisplayName attribute, see this question : DisplayName attribute from Resources?
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "LastNameMandatory")]
[LocalizedDisplayName("LastName")]
public string RenterLastName { get; set; }
The LocalizedDisplayName works well if your solution allows you to work with resource strings. unfortunately in my project we have several languages and growing... and the translations are all maintained in the database.
We have therefore taken the approach to
inherit from the attribute in our own dll, and
then get the default format string and use that as a base value for our messages
have our translation factory get the value or register the default in the database
then we import the namespace and give it an alias, the implemented version looks something like this:
using tf = MyDating.Translation;
in the ViewViewModel we do:
[tf.DisplayName("Verify Password")]
[DataType(DataType.Password)]
[tf.Compare("Password")]
public string VerifyPassword
{
get;
set;
}
the above CompareAttribute then looks something like this:
public class CompareAttribute : System.ComponentModel.DataAnnotations.CompareAttribute
{
public CompareAttribute(string otherProperty)
:base(otherProperty)
{
var tf = TranslatetionFactory.Current.GetSection("CompareAttribute");
var msg = tf.Get(this.ErrorMessageString);
ErrorMessage = msg;
}
}