PostUrlEncodedAsync with complex object - flurl

Hi I'm trying to post an object that is like :
public class myobj
{
public string name {get;set;}
public myEntity myentity {get;set;}
public mySecondEntity mySecondEntity {get;set;}
}
public class myEntity {get;set;}
{
public string name {get;set;}
public string description {get;set;}
}
public class mySecondEntity {get;set;}
{
public string name {get;set;}
public string description {get;set;}
}
When I use generate a new object of myObj and use PostUrlEncodedAsync it is posting it as :
name : "myname",
myentity : "detex.Models.DTO.myEntity",
mysecondentity : "detex.Models.DTO.mySecondEntity
Not sure what my namespace/class is doing in those fields. I'm posting this as
await "myurl.com".PostUrlEncodedAsync(_model).

Flurl assumes that objects passed to PostUrlEncodedAsync represent simple name/value pairs. It simply does a ToString on your values, which is why you're getting detex.Models.DTO.myEntity. Do you want those values serialized to JSON? If so you'll need to do that yourself:
"myurl.com".PostUrlEncodedAsync(new {
name = _model.name,
myentity = JsonConvert.SerializeObject(_model.myentity),
mysecondentity = JsonConvert.SerializeObject(_model.mySecondEntity)
});
Posting complex objects as URL-encoded is not typical, which is why serializing those values is not built into Flurl.

Related

Handling Uknown string Value to deserialize as default Enum

I am trying to deserialize my API request body to object.
My json looks like this:
{
"EmployeeId": 123,
"EmployeeName": "Tony",
"EmployeeType": "Contractor"
}
My Class looks like:
public class RequestDto
{
public int EmployeeId {get; set;}
public string EmployeeName {get; set;}
public EmployeeType {get; set;}
}
My EmployeeType Enum
public enum EmployeeType
{
Uknown,
FullTime,
Vendor
}
I am using .net core 3.1 and i have added newtonsoft converters stringEnumConverter() in my startup.cs as well. with the above json, im getting an error converting the value to enum. I want it to be converted to default enum value when there is an unknown string value which is not available in the enum class. Is there any way .net core/newtonsoft allows me to do it without adding any custom converters which inherits from StringEnumConverter().

Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData

I am getting this error when trying to Deserialize the string from the redis cache using Newtonsoft.Json.
where HeaderTopViewComponent is model class of one of my view component ""
like: JsonConvert.DeserializeObject<HeaderTopViewComponent>(cacheValue.Result.ToString());
Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData. Path 'ViewBag', line 1, position 340.
Output string :
{"ShowTopheaderSection":true,"PageHeader":"MSHSL","FriendlyURL":"/MSHSL","leagueList":[{"leagueId":0,"FriendlyURL":"/","leaguename":"--Select--"},{"leagueId":3,"FriendlyURL":"/MSHSL","leaguename":"MSHSL"},{"leagueId":4,"FriendlyURL":"/CHSAA","leaguename":"CHSAA"}],"HttpContext":null,"Request":null,"User":null,"RouteData":null,"ViewBag":{},"ModelState":{},"Url":null,"ViewComponentContext":{"Arguments":null,"HtmlEncoder":null,"ViewComponentDescriptor":{"DisplayName":null,"FullName":null,"Id":"9882d08a-1c50-4c59-8a30-2d9c843957e9","ShortName":null,"TypeInfo":null,"MethodInfo":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"Writer":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"ViewEngine":null}
I have fix it by adding some tag in my viewcomponent modal class and get set property like
[JsonObject(MemberSerialization.OptIn)] and [JsonProperty]
//Tag to add only selected property when Deserialize or Serialize using Newtonsoft
[JsonObject(MemberSerialization.OptIn)]
public class HeaderTopViewComponent:ViewComponent
{
#region //Property//
[JsonProperty]
public bool ShowTopheaderSection { get; set; }
[JsonProperty]
public string PageHeader { get; set; }
[JsonProperty]
public string FriendlyURL { get; set; }
[JsonProperty]
And now its working

create web service with 200 input parameter which is the optimized way and how?

I want to create a webs-service with 200 input parameters Using Asp.Net. previously I have managed with 100+ parameter using class objects. This time with more parameter with more datatype lengths. I prefer xml for this.
But I need expertise advise for optimized way and how. Idea about performance point of view also.
Appreciate you advise. Thanks
Finally I have created a web service with custom class object as parameter.My custom class object which consist of 185 properties. I have exported the inputs of custom class objects to sample.xml file.
[WebMethod]
public string SubmittoSOT(XXSampleObjects sampleobjects)
{
XmlSerializer serializer = new XmlSerializer(typeof(XXSampleObjects ));
string filepath = Server.MapPath("File/sample.xml");
using (TextWriter writer = new StreamWriter(filepath))
{
serializer.Serialize(writer, sampleobjects);
}
return "1";
}
[Serializable]
public class XXSampleObjects
{
public int param1 {get;set;}
public int param2 {get;set;}
public DateTime param3 {get;set;}
public string param4 {get;set;}
public decimal param5 {get;set;}
public decimal param6 {get;set;}
public string param7 {get;set;}
public decimal param8 {get;set;}//money datatype
public int param9 {get;set;}
}

ASP.NET MVC3 EF model Inheritance Cannot implicitly convert type

I am sure i am just missing some pretty basic here, but i can't seem to figur it out.. maybe because its been a while since i have been on the .NET platform.
Anyway, I have this database structure i the ASP.NET MVC3 framework where i have "Coruse", "Tool" and "ToolADL"(Inheritance from Tool). A "Course" can have one-or-more "Tools" where one of the "Tool"-types is "ToolADL".
Models/Course.cs:
public class Course {
[Key]
public int CourseID { get; set; }
[Required(ErrorMessage = "{0} er påkrævet")]
[Display(Name = "Værktøj")]
public virtual ICollection<Tool> Tools { get; set; }
}
Models/Tool.cs:
public abstract class Tool {
public Tool(){
Priority = 0;
}
[Key]
public int ToolID { get; set; }
[Required]
public int CourseID { get; set; }
[Required]
public int Priority { get; set; }
}
Models/ToolADL.cs:
public class ToolADL : Tool {
[Required]
public string Image { get; set; }
}
aaand the Models/ProjectContext:
public class ProjectContext : DbContext {
// Course context
public DbSet<Course> Courses { get; set; }
// Tools
public DbSet<Tool> Tools { get; set; }
// ToolADL
public DbSet<ToolADL> ToolADLs { get; set; }
}
Now when i try to create the controller and connect to DbContext and the Model to it so the entity framwork can do its magic, I get the following error in the ToolADL controller Details function (and others) where time i use "find()":
ToolADLController.Details(int):
private ProjectContext db = new ProjectContext();
public ViewResult Details(int id){
ToolADL tooladl = db.Tools.Find(id);
return View(tooladl);
}
Error 1 Cannot implicitly convert type 'Project.Models.Tool'
to 'caREhab_community.Models.ToolADL'. An explicit conversion exists
(are you missing a cast?) C:\Users\Thor\Documents\Visual Studio
2010\Projects\Project\Project\Project\ToolADLController.cs 29 31 Project
(I changed the name of the orginal project to "Project")
I simply cannot figur out what I am doing wrong, Is it wrong types, some really basic about Inheritance i left out or something else?
Hope some kind soul can tell me why I am an idiot and can't figure this out :)
If object that is returned by db.Tools.Find(id) is of type ToolADL then you should do:
ToolADL tooladl = db.Tools.Find(id) as ToolADL;
After that You'll have your object or null.
If it's not of type ToolADL then you can't do this because:
When You have:
public class A { }
public class B : A { }
You can not do something like this:
A a = new A();
B b = a;
This is in fact a basic truth about inheritance.
You might change this implicit conversion to explicit on by doing:
B b = (B)a;
Then your code would compile but You would get a runtime exception:
Unable to cast object of type 'A' to type 'B'.
To make it work You would have to specify an explicit conversion like this:
public class A
{
public static explicit operator B(A a)
{
return new B();
}
}
But this will give you yet another compile time error:
'A.explicit operator B(A)': user-defined conversions to or from a
derived class are not allowed

How To Pass JSON into asp.net MVC3 controller formatted like below

I've read Phil's article ( http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx ) and still can't figure out how I can take json that looks like what I have below and pass it into my controller. I don't have much control over formatting it so I need to take it like this and get the data out of it.
{
"Id":"720",
"SponsorName":"Bay Area Association of Database Developers",
"ImageURL":"~/Images/Sponsors/baadd.org.jpg",
"NavigateURL":"http://baadd.org/",
"HoverOverText":"Bay Area Association of Database Developers",
"Comment":"xx"
}
public class SponsorUpdateModel
{
public int Id {get;set;}
public string SponsorName {get;set;}
public string ImageURL {get;set;}
public string NavigateURL {get;set;}
public string HoverOverText {get;set;}
public string Comment {get;set;}
}
public ActionResult Update(SponsorUpdateModel model)
{
}

Resources