Extracting json or object from POST - c#

We have this data
models:"[{"timeTableId":5,"startTime":"2016-06-16T00:00:00","endTime":"2016-06-16T17:00:00","userId":31,"customerId":35}]"
being sent to a asp.net webservice using api.
We cannot determine how to extract the data for manipulation, we have tried...
public IHttpActionResult PostTimeTable([FromBody]string models);// models is null
public IHttpActionResult PostTimeTable(string models);// models is null
public IHttpActionResult PostTimeTable([FromBody]List<TimetableView> models);// models is null
public IHttpActionResult PostTimeTable(IEnumerable<TimetableView> models);// models is null
Where TimetableView is
public class TimetableView
{
public TimetableView(TimeTable timetable)
{
this.TimeTableId = timetable.TimeTableId;
this.StartTime = timetable.StartTime;
this.EndTime = timetable.EndTime;
this.UserId = timetable.UserId;
this.CustomerId = timetable.CustomerId ;
}
public TimetableView(){}
public int TimeTableId { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public int UserId { get; set; }
public int CustomerId { get; set; }
}

try this
public IHttpActionResult PostTimeTable(
int timeTableId,
DateTiem startTime,
DateTime endTime,
int userId,
int customerId);

I have found out why this was not saving or getting the correct information and have solved this.
here is a link to the pastbin: http://pastebin.com/p8HjFdeu

Related

Problem with the DateTime "0001-01-01T00:00:00"

I have a problem with my date. I do the insert with the postman and no matter what I enter I always get back "0001-01-01T00:00:00".
Would also like to limit the output to just the date.
I am very grateful for any help
thank you
Model:
public class BusinessTripDocument
{
public long Id { get; set; }
public string StartLocation { get; set; }
[JsonPropertyName("startDateTime")]
public DateTime StartDate { get; set; }
public string Destination { get; set; }
public DateTime DestinationDate { get; set; }
public string Transportation { get; set; }
public string SuperiorsApproval { get; set; }
// POST: api/Businesstripdocuments
[HttpPost("new/{eId}")]
public async Task<ActionResult<BusinessTripDocument>> PostBusinesstripdocuments(long eId, BusinessTripDocument businesstripdocuments)
{
Employee employee = await _context.Employees.FindAsync(eId);
// businesstripdocuments.Employee = employee;
// _context.Businesstripdocuments.Add(businesstripdocuments);
employee.addDocument(businesstripdocuments);
await _context.SaveChangesAsync();
return CreatedAtAction("GetBusinesstripdocuments", new { id = businesstripdocuments.Id }, businesstripdocuments);
}
Postman
Just from the code you've shown- to me it looks like you should just need to supply the DataType attribute to your Model?
//using System.ComponentModel.DataAnnotations;
public class BusinessTripDocument
{
...
[DataType(DataType.Date)]
[JsonPropertyName("startDateTime")]
public DateTime StartDate { get; set; }
...
}
I suggest that you could do two ways:
1.- The date could be inside the method PostBusinesstripdocuments
2.- The date could be string in class BusinessTripDocument and after conver to datetime.
her is the example:

Asp.Net Core, [FromQuery] complex class

I have the followings classes:
public class TextFilter
{
public string Value { get; set; } = "";
public EnumTextFilterSearchMethod SearchMethod { get; set; } = EnumTextFilterSearchMethod.EQ;
}
public class ContractsFilter
{
public TextFilter ContractNumber { get; set; } = new TextFilter();
public TextFilter OrderNumber { get; set; } = new TextFilter();
}
and controller:
[HttpGet("")]
public IActionResult Contracts([FromQuery] ContractsFilter filter = null)
the query string appears as:
http://localhost:63553/contracts?ContractNumber=my.namespace.TextFilter&OrderNumber=my.namespace.TextFilter
But I would need that the query string is formed as following:
http://localhost:63553/contracts?ContractNumber.Value=any_contract_number&ContractNumber.SearchMethod=EQ&OrderNumber.Value=any_order_number&OrderNumber.SearchMethod=EQ
If I enter so the query string by hand, the controller can it parse properly.
How can I make the class ContractsFilter appears in the query string with all properties of class TextFilter?
Try the [FromUri] attribute before your in-parameter in the same way you’ve tried with the [FromBody] attribute.

Convert CookComputing XMLRpcStruct (IEnumerable<Object>) to an actual C# class

So, I am using CookComputings XMLRPC library to be able to talk to InfusionSoft (it's an online CRM that's quite popular). The main method is:
[XmlRpcMethod("DataService.query")]
IEnumerable<object> QuerySubscriptionStatus(string apiKey,
string table, int limit, int page,
IDictionary queryData, string[] selectedFields);
I am REQUIRED to use an IEnumerable<object> sadly, as the InfusionSoft XML/RPC API requires it. I wish it wasn't the case, but sadly it is.
Since I use .NET 4.5, I figured I can just do a dynamic cast:
var subStatus = proxy.QuerySubscriptionStatus(
_key, "RecurringOrder", 500, 0, dict, sarray);
var result = subStatus.Cast<SubscriptionStatus>();
Unfortunately, this doesn't work, I'm given a very upset error from C#:
Unable to cast object of type 'CookComputing.XmlRpc.XmlRpcStruct' to type 'WBI.Model.SubscriptionStatus'.`
I've tried specifying my class as a struct; heck I've even tried specifying it with XMLRpcMember() tags, but nope, it just wont convert.
How can I interact with the data in the IEnumerable?
Class/Struct Types I've Tried
public struct SubStatus
{
public int AffiliateId;
public int AutoCharge;
public double BillingAmt;
public string BillingCycle;
public int CC1;
public int CC2;
public int ContactId;
public DateTime EndDate;
public int Frequency;
public int Id;
public DateTime LastBillDate;
public int LeadAffiliateId;
public int MaxRetry;
public int MerchantAccountId;
public DateTime NextBillDate;
public int NumDaysBetweenRetry;
public int OriginatingOrderId;
public DateTime PaidThruDate;
public int PaymentGatewayId;
public int ProductId;
public int ProgramId;
public string PromoCode;
public int Qty;
public string ReasonStopped;
public int ShippingOptionId;
public DateTime StartDate;
public string Status;
public int SubscriptionPlanId;
}
I also just tried a simple class with the XMLRpcMember tags:
public class SubscriptionStatus
{
[XmlRpcMember("AffiliateId")]
public int AffiliateId { get; set; }
[XmlRpcMember("AutoCharge")]
public int AutoCharge { get; set; }
[XmlRpcMember("BillingAmt")]
public double BillingAmt { get; set; }
[XmlRpcMember("BillingCycle")]
public string BillingCycle { get; set; }
[XmlRpcMember("CC1")]
public int CC1 { get; set; }
[XmlRpcMember("CC2")]
public int CC2 { get; set; }
[XmlRpcMember("ContactId")]
public int ContactId { get; set; }
[XmlRpcMember("EndDate")]
public DateTime EndDate { get; set; }
[XmlRpcMember("Frequency")]
public int Frequency { get; set; }
[XmlRpcMember("Id")]
public int Id { get; set; }
[XmlRpcMember("LastBillDate")]
public DateTime LastBillDate { get; set; }
[XmlRpcMember("LeadAffiliateId")]
public int LeadAffiliateId { get; set; }
[XmlRpcMember("MaxRetry")]
public int MaxRetry { get; set; }
[XmlRpcMember("MerchantAccountId")]
public int MerchantAccountId { get; set; }
[XmlRpcMember("NextBillDate")]
public DateTime NextBillDate { get; set; }
[XmlRpcMember("NumDaysBetweenRetry")]
public int NumDaysBetweenRetry { get; set; }
[XmlRpcMember("OriginatingOrderId")]
public int OriginatingOrderId { get; set; }
[XmlRpcMember("PaidThruDate")]
public DateTime PaidThruDate { get; set; }
[XmlRpcMember("PaymentGatewayId")]
public int PaymentGatewayId { get; set; }
[XmlRpcMember("ProductId")]
public int ProductId { get; set; }
[XmlRpcMember("ProgramId")]
public int ProgramId { get; set; }
[XmlRpcMember("PromoCode")]
public string PromoCode { get; set; }
[XmlRpcMember("Qty")]
public int Qty { get; set; }
[XmlRpcMember("ReasonStopped")]
public string ReasonStopped { get; set; }
[XmlRpcMember("ShippingOptionId")]
public int ShippingOptionId { get; set; }
[XmlRpcMember("StartDate")]
public DateTime StartDate { get; set; }
[XmlRpcMember("Status")]
public string Status { get; set; }
[XmlRpcMember("SubscriptionPlanId")]
public int SubscriptionPlanId { get; set; }
}
So, after some extended help from another senior developer, it turns out we were able to make some changes to the struct:
private string[] retFlds = { "Id", "ContactId", "OriginatingOrderId", "ProgramId", "SubscriptionPlanId", "ProductId", "StartDate", "NextBillDate", "BillingCycle", "Frequency", "BillingAmt", "Status", "ReasonStopped", "AutoCharge", "CC1", "CC2", "NumDaysBetweenRetry", "MaxRetry", "MerchantAccountId", "AffiliateId", "PromoCode", "LeadAffiliateId", "Qty", "ShippingOptionId" };
private string table = "RecurringOrder";
private DataTable dt = new DataTable();
// here's the query
XmlRpcStruct[] retData = proxy.Query(Auth.key, table, 1000, 0, qryData, returnFields);
dt = StructArrayToDT(retData);
public static DataTable StructArrayToDT(XmlRpcStruct[] data)
{
DataTable dt = new DataTable();
if (data.Length == 0) { return dt; }
// do columns
foreach (DictionaryEntry d in data[0])
{
dt.Columns.Add(d.Key.ToString(), typeof(object));
}
foreach (XmlRpcStruct xmlstruct in data)
{
DataRow dr = dt.NewRow();
foreach (DictionaryEntry d in xmlstruct)
{
try
{
dr[d.Key.ToString()] = d.Value;
}
catch (Exception ex)
{
// handle errors
}
}
dt.Rows.Add(dr);
}
return dt;
}
Finally can access that data without any issue now.
Looking at signature of QuerySubscriptionStatus its returning IEnumerable. Again if you look at definition of XmlRpcStruct (Fork of XML.Rpc.Net) which is implementing IDictionary, ICollection, IEnumerable. So if we assume that QuerySubscriptionStatus is returning XmlRpcStruct which implements IEnumerable then you are getting Enumeration in response which is essentially collection of items (even if it contains single item). You are trying to typecast Enumeration to structure (SubscriptionStatus) which is not collection. Hence the error.
If items contained in Enumeration are of type SubscriptionStatus structure then following line should do trick.
var resultList = subStatus.ToList<SubscriptionStatus();
and then loop through resultList to access response from QuerySubscriptionStatus method.
foreach(var result in resultList)
{
}
OR if you are sure that response list will have single entry then you may also use following
var result = resultList.FirstOrDefault();
Hope that helps.

Newtonsoft.Json not working for one string field and one datetime field

I'm using Newtonsoft.Json on PCL project for a Xamarin.Android project.
This is how I used it:
var r = await _client.GetAsync("users/login?email=" + e+ "&password=" + p);
string c = await r.Content.ReadAsStringAsync();
var dtC= new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd hh:mi:ss:mmm" };
return string.IsNullOrEmpty(c) ? new Transporter<User>() :
JsonConvert.DeserializeObject<Transporter<User>>(c, dtC);
Transporter is a json helper and its class is (short version):
public class Transporter<T>
{
public T data;
private bool success = true;
public Transporter()
{
}
public bool isSuccess()
{
return success;
}
public void setSuccess(bool success)
{
this.success = success;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
}
And the User class:
[Table("User")]
public class User
{
[PrimaryKey, AutoIncrement]
public long Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public DateTime CreationDate { get; set; }
}
All properties of User comes right from the server. All filled up.
But when I do the deserialization - JsonConvert.DeserializeObject<Transporter<User>>(c, dtC) - the property LastName is null and the property CreationDate is 0001-01-01T00:00:00.0000000Z.
EDIT:
{"data":{"id":2,"name":"test","last_name":"test 1","email":"test2","password":"aaa","creation_date":"2016-09-20T21:13:22.18"},"success":true}
The format yyyy-MM-dd hh:mi:ss:mmm is invalid, because it has the colon : just before the milliseconds part. Should it be yyyy-MM-dd hh:mi:ss.mmm.

Asp.net web api GetAll return null after doing POST

when I testing(with Fiddler Web Debugger) to insert or POST a data to the province through web api the data is inserted to the database normally but when I access the GetAll web api service the Country is returning null :
http://localhost:51372/api/province/
but after I doing Rebuild Solution from my VS 2013 Express For Web Edition, then access the getAll service from web api once again I got the Country is returning the value :
how can I get the Country is returning the value right after I doing POST data ?
this is the detail code that I use
the models :
public class Province
{
public int ProvinceId { get; set; }
[Required]
public string ProvinceName { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
//Foreign Key
[ForeignKey("Country")]
public int CountryId { get; set; }
//virtual
public virtual Country Country { get; set; }
}
public class Country
{
[ScaffoldColumn(false)]
public int CountryId { get; set; }
[Required]
[Index(IsUnique=true)]
[MaxLength(200)]
public string CountryName { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
Repository :
private SelsContext db = new SelsContext();
//get all provinces
public IEnumerable<Province> GetAllProvince()
{
IEnumerable<Province> provinces = from c in db.Provinces select c;
return provinces;
}
//post provinces
public Models.Province Add(Models.Province item)
{
item.CreatedAt = DateTime.Now;
item.UpdatedAt = DateTime.Now;
db.Provinces.Add(item);
db.SaveChanges();
return item;
}
controller :
// GET api/province
[Queryable]
public IQueryable<Province> Get()
{
return repository.GetAllProvince().AsQueryable();
}
// POST api/province
public HttpResponseMessage Post([FromBody]Province value)
{
repository.Add(value);
var response = Request.CreateResponse<Province>(HttpStatusCode.Created, value);
string uri = Url.Link("DefaultApi", new { id = value.ProvinceId });
response.Headers.Location = new Uri(uri);
return response;
}
EDIT :
I've tried so far
in repository :
public IEnumerable<Province> GetAllProvince()
{
IEnumerable<Province> provinces = db.Provinces.Include("Country");
return provinces;
}
then
public IEnumerable<Province> GetAllProvince()
{
IEnumerable<Province> provinces = db.Provinces.SqlQuery("select * from dbo.Provinces left join dbo.Countries on dbo.Countries.CountryId=dbo.Provinces.CountryId");
return provinces;
}
but get the same result.
any help would be much apreciated.
In your repository, can you do:
IEnumerable<Province> provinces = db.Provinces.Include("Country");

Categories