WCF Rest Service Request Object' s Fields Always Null - json

I created a WCF Rest Service. I try to Post method usage. I send request from client, request getting from service method. But request object (CompanyDTO) fields values are null. Where is problem? I could' nt find.
Service post method
public void SaveCompany(CompanyDTO NewCompany)
{
try
{
CompanyManager manager = new CompanyManager();
manager.Save(NewCompany);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new FaultException(new FaultReason(ex.Message));
}
}
Contract service interface
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "SaveCompany")]
void SaveCompany(CompanyDTO NewCompany);
CompantDTO class
public class CompanyDTO
{
public string IDENTIFIER { get; set; }
public string TYPE { get; set; }
public string USER_TYPE { get; set; }
public string FIRST_NAME { get; set; }
public string MIDDLE_NAME { get; set; }
public string FAMILY_NAME { get; set; }
public string COMPANY_NAME { get; set; }
public Nullable<int> COMPANY_NO { get; set; }
public string LEGAL_OFFICE { get; set; }
public Nullable<System.DateTime> FOUNDATION_DATE { get; set; }
public string BOARDOFTRADE_NAME { get; set; }
public string BOARDOFTRADE_ID { get; set; }
public string MERSIS_NO { get; set; }
public string TAPDK_NO { get; set; }
public string TRADE_REGISTRATION_NO { get; set; }
public string TRADE_REGISTRATION_OFFICE { get; set; }
public string TAX_IDENTIFICATION_NO { get; set; }
public Nullable<System.DateTime> DIGITAL_SIGN_VALIDITY_DATE { get; set; }
public string TAX_OFFICE { get; set; }
public string TAX_OFFICE_CODE { get; set; }
public Nullable<short> STATUS { get; set; }
public Nullable<int> SYS_VERSION { get; set; }
public Nullable<System.DateTime> SYS_LAST_UPDATE { get; set; }
}
Client request body
{
"CompanyDTO":
{
"IDENTIFIER":"34501599398",
"TYPE":"1",
"USER_TYPE":"1",
"FIRST_NAME":"Ebru",
"MIDDLE_NAME":"sws",
"FAMILY_NAME":"sd",
"COMPANY_NAME":"NULL",
"COMPANY_NO": "123",
"LEGAL_OFFICE": "DSF",
"FOUNDATION_DATE":"2015-03-02",
"BOARDOFTRADE_NAME":"SAD",
"BOARDOFTRADE_ID":"ASD",
"MERSIS_NO":"DASD",
"TAPDK_NO":"NULASDASDL",
"TRADE_REGISTRATION_NO":"NULL",
"TRADE_REGISTRATION_OFFICE":"ADS",
"TAX_IDENTIFICATION_NO":"NUASDSALL",
"DIGITAL_SIGN_VALIDITY_DATE": "2015-03-02",
"TAX_OFFICE":"ASDAD",
"TAX_OFFICE_CODE":"ASDA",
"STATUS": "1",
"SYS_VERSION" : "1",
"SYS_LAST_UPDATE": "2015-03-02"
}
}

It seems you need to get rid of "CompanyDTO" in your json, so it looks likes this:
{
"IDENTIFIER":"34501599398",
"TYPE":"1",
"USER_TYPE":"1",
"FIRST_NAME":"Ebru",
"MIDDLE_NAME":"sws",
"FAMILY_NAME":"sd",
"COMPANY_NAME":"NULL",
"COMPANY_NO": "123",
"LEGAL_OFFICE": "DSF",
"FOUNDATION_DATE":"2015-03-02",
"BOARDOFTRADE_NAME":"SAD",
"BOARDOFTRADE_ID":"ASD",
"MERSIS_NO":"DASD",
"TAPDK_NO":"NULASDASDL",
"TRADE_REGISTRATION_NO":"NULL",
"TRADE_REGISTRATION_OFFICE":"ADS",
"TAX_IDENTIFICATION_NO":"NUASDSALL",
"DIGITAL_SIGN_VALIDITY_DATE": "2015-03-02",
"TAX_OFFICE":"ASDAD",
"TAX_OFFICE_CODE":"ASDA",
"STATUS": "1",
"SYS_VERSION" : "1",
"SYS_LAST_UPDATE": "2015-03-02"
}

Related

Post Request gives a 405 error in Postman

on my .Net Web Api, I have an entity model, request model and response model for each database table. When i make a post request to MedTestOrder, i receive a 405 error, but other entities are working fine. I will post code snippets of MedTestOrder entity model, request model, response model, controller and service. The models contain foreign keys and I suspect my error could be from there. I might be wrong or not. I just need help.
1 - Entity Model
namespace Africanbiomedtests.Entities
{
public class MedTestOrder
{
[Key]
public int Id { get; set; }
public int? MedTestId { get; set; }
[ForeignKey("MedTestId")]
public MedTest MedTest { get; set; }
public int? healthcareProviderId { get; set; }
[ForeignKey("healthcareProviderId")]
public HealthcareProvider healthcareProvider { get; set; }
public int? accountId { get; set; }
[ForeignKey("accountId")]
public Account Account { get; set; }
public int? newbornId { get; set; }
[ForeignKey("newbornId")]
public Newborn Newborn { get; set; }
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateCompleted { get; set; }
public DateTime? Updated { get; set; }
}
}
2 - Api Request Model
namespace Africanbiomedtests.Models.MedTestsOrder
{
public class MedTestsOrderCreateRequest
{
[Required]
public MedTest MedTest { get; set; }
public HealthcareProvider healthcareProvider { get; set; }
public Account Account { get; set; }
public Newborn Newborn { get; set; }
[Required]
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
[Required]
public DateTime DateCreated { get; set; }
}
}
3 - Response Model
namespace Africanbiomedtests.Models.MedTestsOrder
{
public class MedTestsOrderResponse
{
public int Id { get; set; }
public MedTest MedTest { get; set; }
public HealthcareProvider healthcareProvider { get; set; }
public Account Account { get; set; }
public Newborn Newborn { get; set; }
public string PaymentStatus { get; set; }
public Boolean CompletionStatus { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateCompleted { get; set; }
}
}
4 - Controller
[Authorize]
[HttpPost("create")]
public ActionResult<MedTestsOrderResponse> Create(MedTestsOrderCreateRequest model)
{
var medTestOrder = _medTestOrderService.Create(model);
return Ok(medTestOrder);
}
5 - Service
public MedTestsOrderResponse Create(MedTestsOrderCreateRequest model)
{
// map model to new account object
var medTestOrder = _mapper.Map<MedTestOrder>(model);
medTestOrder.DateCreated = DateTime.UtcNow;
// save account
_context.MedTestOrder.Add(medTestOrder);
_context.SaveChanges();
return _mapper.Map<MedTestsOrderResponse>(medTestOrder);
}
6 - Postman JSON request
{
"medTestId": 3,
"healthcareProviderId": 3,
"accountId": 1004,
"newbornId": 1,
"paymentStatus": "Complete Payment",
"completionStatus": "1",
"dateCompleted": "01/14/2021"
}
I would really appreciate any help right now
Thank you #Marius and #Karney, I realized i wasn't using the correct endpoint. I needed to add "/create" to my endpoint.
In some cases, your Web API method accepts only PUT requests, Try to put not post.

Deserializing a JSON stream from an API in .Net Core 3.0 leaving all fields null

I've got a simple WPF / .Net Core 3.0 app which executes a GET on a Web API endpoint:
private HttpClient httpClient = new HttpClient();
private async Task GetClients()
{
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>));
var streamTask = httpClient.GetStreamAsync("https://mywebapp.com/api/Clients");
List<ClientGetDto> clientDtos = serializer.ReadObject(await streamTask) as List<ClientGetDto>;
}
ClientGetDto looks like this:
{
public int Id { get; set; }
public string ClientCode { get; set; }
public string ApiUrl { get; set; }
public string CompanyName { get; set; }
public string FranchiseName { get; set; }
public int? ProLicenses { get; set; }
public int? LiteLicenses { get; set; }
public int? ProSalesLicenses { get; set; }
public int? LiteSalesLicenses { get; set; }
public bool? IsActive { get; set; }
public DateTime? StartOfAgreementDate { get; set; }
public int? DebitOrderDay { get; set; }
public DateTime? DebitOrderStartDate { get; set; }
public decimal? ContractAmount { get; set; }
public bool? DebitOrderFormReceived { get; set; }
public bool? CancellationReceived { get; set; }
public DateTime? CancellationDate { get; set; }
public string CompanyRegNo { get; set; }
public string DbUrl { get; set; }
public string DbName { get; set; }
public double? CloudStorageQuota { get; set; }
public string Comments { get; set; }
public int? FranchiseId { get; set; }
public bool? IsTestDb { get; set; }
public bool? IsGumtreeRegistered { get; set; }
public int? FusionClientId { get; set; }
public string CountryCode { get; set; }
}
and the JSON that is returned by the API is:
[
{
"id": 3,
"clientCode": "cx0007",
"apiUrl": "https://mywebapp/api",
"companyName": "ACME Company",
"franchiseName": "ACME Franchise",
"proLicenses": 1,
"liteLicenses": 0,
"proSalesLicenses": 0,
"liteSalesLicenses": 0,
"isActive": true,
"startOfAgreementDate": "2007-08-01T00:00:00",
"debitOrderDay": 1,
"debitOrderStartDate": "2012-03-01T00:00:00",
"contractAmount": 695.00,
"debitOrderFormReceived": true,
"cancellationReceived": false,
"cancellationDate": "2012-10-18T00:00:00",
"companyRegNo": "",
"dbUrl": "mydb.co.za",
"dbName": "db1",
"cloudStorageQuota": 5.0,
"comments": null,
"franchiseId": null,
"isTestDb": false,
"isGumtreeRegistered": false,
"fusionClientId": null,
"countryCode": "US"
},
...
]
My problem is that the code is correctly deserializing the JSON into a List of ClientGetDto objects, but all the fields are null. It's not throwing any exceptions or anything. I've tried decorating my ClientGetDto model with [DataContract] and [DataMember] but it's made no difference (nor would it, since the names of the fields of the model are exactly the same as those in the JSON data)
Any ideas?
You should mark each property with [JsonPropertyName("")] because json is case sensitive (I think).

Get item from JSON Odata list for UWP

I have been having a hard time trying to figure this out that I've just about torn out all my hair now.
Using this section of code (Added a var result that I looking at with a stoppoint):
public async Task<string> GetHttpSPContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SharePointListItems.Fields>(content);
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
The content that I receive is this (updated getting rid of extra information):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items/$entity",
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"createdDateTime": "2018-08-07T14:28:47Z",
"eTag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"id": "1",
"lastModifiedDateTime": "2018-08-07T14:28:47Z",
"webUrl": "https://XXXX.sharepoint.com/Lists/TestList/1_.000",
"createdBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"parentReference": {},
"contentType": {
"id": "0x010001403BD420356E4ABE3B63E5AEC0713D"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items('1')/fields/$entity",
"fields": {
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"Title": "1",
"UserName": "TK",
"UserAge": "47",
"UserTitle": "Developer"
}
}
I just want the values forUserAge, UserName, and UserTitle to put each into a textbox, but not sure how to pull them out.
I am pretty sure that I need to set up a class of some sort, but it is the #odata parts that are breaking my back.
Everything that I have tried just gives me back a null value. I see the value there, just not sure how to parse/pull it out.
I have looked at this (updated):
using Newtonsoft.Json;
using System;
public class SharePointListItems
{
public class UserCreated
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class CreatedBy
{
public UserCreated user { get; set; }
}
public class UserModified
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class LastModifiedBy
{
public UserModified user { get; set; }
}
public class ParentReference
{
}
public class ContentType
{
public string id { get; set; }
}
public class Fields
{
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public string Title { get; set; }
public string UserName { get; set; }
public string UserAge { get; set; }
public string UserTitle { get; set; }
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public DateTime createdDateTime { get; set; }
public string eTag { get; set; }
public string id { get; set; }
public DateTime lastModifiedDateTime { get; set; }
public string webUrl { get; set; }
public CreatedBy createdBy { get; set; }
public LastModifiedBy lastModifiedBy { get; set; }
public ParentReference parentReference { get; set; }
public ContentType contentType { get; set; }
[JsonProperty("fields#odata.context")]
public string FieldsODataContext { get; set; }
public Fields fields { get; set; }
}
}
But then I run into the issue that there is two [JsonProperty("#odata.etag")].
The [JsonProperty] custom attribute is added to the C# property that actually holds that value. Instead of putting the attribute on the Title or createDateTime property, you need to put them on their own properties:
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
// No attribute needed here
public DateTime createdDateTime { get; set; }
// etc...
Also, you are trying to parse the content as a Fields class, but it is a RootObject; you need to use
JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content)
To get the object.

Deserialize OneNote Notebooks API Response

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}
You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

How can I parse the following JSON for WP7 and bind to a listbox?

I'm having some trouble binding this json to a ListBox...The problem seems to happen in the ActivityTrack class/object of the JSON...i'm not sure what is not meshing...
{"collection":[{"type":"track","created_at":"2011/09/18 14:04:00 +0000","origin":{"id":23606164,"created_at":"2011/09/18 14:03:59 +0000","user_id":222927,"duration":342465,"commentable":true,"state":"finished","sharing":"public","tag_list":"garage usgarage soulfulhouse house deephouse deep","permalink":"pablo-cortez-when-i-need-u","description":"","streamable":true,"downloadable":false,"genre":"UK Garage","release":"","purchase_url":null,"label_id":null,"label_name":"","isrc":"","video_url":null,"track_type":"demo","key_signature":"","bpm":null,"title":"Pablo Cortez - When I Need U (Back To 90s Mix)","release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/23606164","permalink_url":"http://soundcloud.com/pablocortez/pablo-cortez-when-i-need-u","artwork_url":null,"waveform_url":"http://w1.sndcdn.com/wuiZilHRZhl6_m.png","user":{"id":222927,"permalink":"pablocortez","username":"Pablo Cortez","uri":"https://api.soundcloud.com/users/222927","permalink_url":"http://soundcloud.com/pablocortez","avatar_url":"http://i1.sndcdn.com/avatars-000000771958-y059w8-large.jpg?ca13f03"},"stream_url":"https://api.soundcloud.com/tracks/23606164/stream","user_playback_count":1,"user_favorite":false,"playback_count":28,"download_count":0,"favoritings_count":0,"comment_count":2,"attachments_uri":"https://api.soundcloud.com/tracks/23606164/attachments","sharing_note":{"text":"My new sounds","created_at":"2011/09/18 14:03:59 +0000"}},"tags":"affiliated"}],"next_href":"https://api.soundcloud.com/me/activities/track.json?cursor=86db5e5e-e1fe-11e0-9c69-0f0dad493cfc\\u0026limit=1","future_href":"https://api.soundcloud.com/me/activities/track?uuid%5Bto%5D=2d9c67ee-e22f-11e0-94fa-45aa16adeba3"}
Here is the class structure which i am trying to bind the JSON too
public class Activities
{
public ActivityTrack [] activities { get; set; }
public string next_href { get; set; }
public string future_href { get; set; }
}
public class ActivityTrack
{
public string type { get; set; }
public string created_at { get; set; }
public OriginActivityTrack origin { get; set; }
public string tags { get; set; }
}
public class OriginActivityTrack
{
public string id { get; set; }
public string created_at { get; set; }
public string user_id { get; set; }
public string duration { get; set; }
public string commentable { get; set; }
public string state { get; set; }
public string sharing { get; set; }
public string tag_list { get; set; }
public string permalink { get; set; }
public string description { get; set; }
public string streamable { get; set; }
public string downloadable { get; set; }
public string genre { get; set; }
public string release { get; set; }
public string purchase_url { get; set; }
public string label_id { get; set; }
public string label_name { get; set; }
public string isrc { get; set; }
public string video_url { get; set; }
public string track_type { get; set; }
public string key_signature { get; set; }
public string bpm { get; set; }
public string title { get; set; }
public string release_year { get; set; }
public string release_month { get; set; }
public string release_day { get; set; }
public string original_format { get; set; }
public string license { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string artwork_url { get; set; }
public string waveform_url { get; set; }
public SmallUser user { get; set; }
public string stream_url { get; set; }
public string user_playback_count { get; set; }
public string user_favorite { get; set; }
public string playback_count { get; set; }
public string download_count { get; set; }
public string favoritings_count { get; set; }
public string comment_count { get; set; }
public string attachments_uri { get; set; }
public SharingNote sharing_note;
}
public class SharingNote
{
public string text { get; set; }
public string created_at { get; set; }
}
public class SmallUser
{
public string id { get; set; }
public string permalink { get; set; }
public string username { get; set; }
public string uri { get; set; }
public string permalink_url { get; set; }
public string avatar_url { get; set; }
}
This is the current code for binding to listbox:
private void ReadCallbackDashboard(IAsyncResult asynchronousResult)
{
lock (locker)
{
try
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 =
new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultString)))
{
if (ms != null)
{
var ser = new DataContractJsonSerializer(typeof(Activities));
Activities obj = (Activities)ser.ReadObject(ms);
userDashboardActivities = null;
userDashboardActivities = new ObservableCollection<ActivityTrack>();
for (int i = 0; i < obj.activities.Length; ++i)
{
userDashboardActivities.Add(obj.activities[i]);
}
if (userDashboardActivities.Count() == 0)
{
messageDashboard = "No Tracks Found";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
}
else
{
messageDashboard = "";
UIThread.Invoke(() => mainMessage.Text = messageDashboard);
UIThread.Invoke(() => dashboardBox.ItemsSource = userDashboardActivities);
}
}
}
}
}
catch (WebException we)
{
UIThread.Invoke(() => MessageBox.Show("Could not retrieve the latest. Internet down? Try a refresh."));
}
}
}
please check it out! Thanks in advance!
Answer as discovered in the comments.
You have called your property activities but the json calls it collection.