I am trying to post data to a web api with this structure:
Ledger Header and a list of ledger details. This is my class in the web api for the two:
public class PropertyLedgerDetail
{
[Key]
public int LedgerDetailID { get; set; }
public int LedgerID { get; set; }
public int? TransactionID { get; set; }
public int? TransactionTypeID { get; set; }
public double? Amount { get; set; }
public double? PaymentAmount { get; set; }
public int Month { get; set; }
public int Year { get; set; }
[StringLength(1000)]
public string Remarks { get; set; }
public bool Voided { get; set; }
public DateTime? PostingDateTime { get; set; }
}
public class PropertyLeger
{
[Key]
public int LedgerID { get; set; }
public int CollectingAgentID { get; set; }
public int UnitID { get; set; }
public int PaymentTypeID { get; set; }
[StringLength(15)]
public string ORNumber { get; set; }
public int? VoidedLedgerID { get; set; }
public bool? Voided { get; set; }
[StringLength(100)]
public string Remarks { get; set; }
public DateTime? TransactionDateTime { get; set; }
public DateTime? PostingDateTime { get; set; }
}
and this is to combine the two classes so I can receive it from my frontend:
public class AddLedger
{
public PropertyLeger PropertyLedger { get; set; }
public List<PropertyLedgerDetail> PropertyLedgerDetails { get; set; }
}
In my Angular front end, this is how I set up the properties to send:
Get values from 2 forms
add() {
const PropertyLedgerModel: any = {
CollectingAgentID: this.CollectingAgentID.value,
UnitID: this.unitId,
PaymentTypeID: this.PaymentTypeID.value,
ORNumber: this.ORNumber.value,
VoidedLedgerID: this.VoidedLedgerID.value,
Voided: this.Voided.value,
Remarks: this.Remarks0.value
}
const PropertyLedgerDetailsModel: any[] = this.dataSource;
const model: any = {
PropertyLedger: PropertyLedgerModel,
PropertyLedgerDetails: PropertyLedgerDetailsModel
}
this.pps.addLedger(model)
.subscribe((data: any) => {
debugger;
if (data.StatusCode === 200) {
this.ts.success(data.ReasonPhrase);
} else {
this.ts.error(data.ReasonPhrase);
}
},
err => {
this.ts.error('An error has occured in saving payment(s): ' +err);
})
}
To actually send this to the web api
addLedger(model: any) {
debugger;
const ep = this.rootUrl + '/api/newpropertyledger';
const PropertyLedgerModel: any = model.PropertyLedger;
const PropertyLedgerDetailsModel: any [] = model.PropertyLedgerDetails;
const Model: any = {
PropertyLedger: PropertyLedgerModel,
PropertyLedgerDetails: PropertyLedgerDetailsModel
};
return this.http.post(ep, Model);
}
I created a debug point on the part that will receive the data:
but the data from the front end doesn't reach the web api. I just get this error:
Message:"No HTTP resource was found that matches the request URI 'http://localhost:15232/api/newpropertyledger'."
MessageDetail:"No type was found that matches the controller named 'newpropertyledger'."
Please show me how to do it right. Thank you so much.
Assuming your api routing is correct i.e any of the api methods are getting hit, this should help..
addLedger(model: any) {
debugger;
const ep = this.rootUrl + '/api/newpropertyledger';
const PropertyLedgerModel: any = model.PropertyLedger;
const PropertyLedgerDetailsModel: any [] = model.PropertyLedgerDetails;
const Model: any = {
PropertyLedger: PropertyLedgerModel,
PropertyLedgerDetails: PropertyLedgerDetailsModel
};
return this.http.post(ep, JSON.stringify(ledger));
}
public HttpResponseMessage NewPropertyLedger(string data)
{
AddLedger ledger = JsonConvert.DeserializeObject<AddLedger>(data);
}
I using C# with Web API. I have this server method:
[System.Web.Http.HttpPost]
public HttpResponseMessage Test(CompareOutput model)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
This is my data-model:
public class CompareOutput
{
public CompareOutput(int wc, int source_start, int source_end, int suspected_start, int suspected_end)
{
this.WordsCount = wc;
this.SourceStartChar = source_start;
this.SourceEndChar = source_end;
this.SuspectedStartChar = suspected_start;
this.SuspectedEndChar = suspected_end;
}
public CompareOutput()
{
}
[JsonProperty("wc")]
public int WordsCount { get; set; }
[JsonProperty("SoS")]
public int SourceStartChar { get; set; }
[JsonProperty("SoE")]
public int SourceEndChar { get; set; }
[JsonProperty("SuS")]
public int SuspectedStartChar { get; set; }
[JsonProperty("SuE")]
public int SuspectedEndChar { get; set; }
public override string ToString()
{
return string.Format("{0} -> {1} | {2} -> {3}", this.SourceStartChar, this.SourceEndChar, this.SuspectedStartChar, this.SuspectedEndChar);
}
}
Now, I trying to call this method with this data (placed in BODY of the HTTP request):
{
"wc":11,
"SoS":366,
"SoE":429,
"SuS":393,
"SuE":456
}
This call isn't working. All the int members getting defualt values ("0").
When I trying to send this HTTP-BODY, it's working good:
{
"WordsCount":11,
"SourceStartChar":366,
"SourceEndChar":429,
"SuspectedStartChar":393,
"SuspectedEndChar":456
}
I can understand from that - alternative names (which defined in the model with JsonPropertry attribute) isn't working.
How can I solve it?
Thank you.
Try to decorate your properties this way...
[JsonProperty(PropertyName = "wc")]
public int WordsCount { get; set; }
[JsonProperty(PropertyName = "SoS")]
public int SourceStartChar { get; set; }
[JsonProperty(PropertyName = "SoE")]
public int SourceEndChar { get; set; }
[JsonProperty(PropertyName = "SuS")]
public int SuspectedStartChar { get; set; }
[JsonProperty(PropertyName = "SuE")]
public int SuspectedEndChar { get; set; }
I have two classes that are similar. I'm trying to see if I can simply use one. The first is in our DataModel assembly, and used in our DbContext.
public partial class type210_MotorCarrierFreightInvoice
{
public int MotorCarrierFreightInvoiceId { get; set; } // MotorCarrierFreightInvoiceId (Primary key)
public string InvoiceId { get; set; } // InvoiceId
public DateTime BillDate { get; set; } // BillDate
public string TrackingNumber { get; set; } // TrackingNumber
public decimal NetShipmentCharge { get; set; } // NetShipmentCharge
public long InterchangeTransactionDetailId { get; set; } // InterchangeTransactionDetailId
public long? BillToAddressId { get; set; } // BillToAddressId
public long? ConsigneeAddressId { get; set; } // ConsigneeAddressId
public long? ShipperAddressId { get; set; } // ShipperAddressId
// Foreign keys
public virtual interchange_TransactionDetail interchange_TransactionDetail { get; set; } // fk_Type210_MotorCarrierFreightInvoice_Interchange_TransactionDetail
public virtual typeAny_Address typeAny_Address_BillToAddressId { get; set; }
public virtual typeAny_Address typeAny_Address_ConsigneeAddressId { get; set; }
public virtual typeAny_Address typeAny_Address_ShipperAddressId { get; set; }
public type210_MotorCarrierFreightInvoice()
{
InitializePartial();
}
partial void InitializePartial();
}
The second class should represent the same object.
public class Type210MotorCarrierFreightInvoice
{
public int MotorCarrierFreightInvoiceId { get; set; }
public string InvoiceId { get; set; }
public DateTime BillDate { get; set; }
public string TrackingNumber { get; set; }
public decimal NetShipmentCharge { get; set; }
public long InterchangeTransactionDetailId { get; set; }
public Address BillToAddress { get; set; }
public Address ConsigneeAddress { get; set; }
public Address ShipperAddress { get; set; }
}
I'm working with a WebApi service that will expose the data via JSON. Basically what I'm trying is this:
[Route("api/Subscriber/Get210sNew/{transactionId}")]
[Route("api/Subscriber/Get210sNew/{transactionId}/{limit}")]
public IEnumerable<type210_MotorCarrierFreightInvoice> Get210sDOES_NOT_WORK(int transactionId, int limit = DefaultLimit)
{
var key = new QueryAfterId(transactionId, limit);
var dataService = new Type210DataService(_ediContext);
return dataService
.Get(key)
.Select(x => x);
}
[Route("api/Subscriber/Get210s/{transactionId}")]
[Route("api/Subscriber/Get210s/{transactionId}/{limit}")]
public IEnumerable<type210_MotorCarrierFreightInvoice> Get210sWorks(int transactionId, int limit = DefaultLimit)
{
var key = new QueryAfterId(transactionId, limit);
var dataService = new Type210DataService(_ediContext);
return dataService
.Get(key)
.Select(Map);
}
Here is the Map method:
private static Type210MotorCarrierFreightInvoice Map(
type210_MotorCarrierFreightInvoice dbNotice)
{
return new Type210MotorCarrierFreightInvoice
{
MotorCarrierFreightInvoiceId = dbNotice.MotorCarrierFreightInvoiceId,
InvoiceId = dbNotice.InvoiceId,
BillDate = dbNotice.BillDate,
ShipDate = dbNotice.ShipDate,
TrackingNumber = dbNotice.TrackingNumber,
PurchaseOrderNumber = dbNotice.PurchaseOrderNumber,
BillOfLading = dbNotice.BillOfLading,
NetShipmentCharge = dbNotice.NetShipmentCharge,
InterchangeTransactionDetailId = dbNotice.InterchangeTransactionDetailId,
BillToAddress = Mapper.MapToAddress(dbNotice.typeAny_Address_BillToAddressId),
ConsigneeAddress = Mapper.MapToAddress(dbNotice.typeAny_Address_ConsigneeAddressId),
ShipperAddress = Mapper.MapToAddress(dbNotice.typeAny_Address_ShipperAddressId)
};
}
Get210sWorks will return Json data to the browser. Get210sDOES_NOT_WORK does not. Both queries get the same number of records. But Get210sDOES_NOT_WORK shows no records in the browser window.
Why can't I return an IEnumerable of my DataModel class as Json?
I am attempting to retrieve information using the Steam API. I created the classes offerStuff and itemsClass, offerStuff contains public List<itemsClass> items { get; set; }, however, whenever I attempt to access this list through os.items.Add(item), my program crashes with NullReferenceException. Is there some declaration I am missing? If so, how would I declare it so I can access it without the exception?
public static List<offerStuff> pollOffers()
{
using (dynamic tradeOffers = WebAPI.GetInterface("IEconService", config.API_Key))
{
List<offerStuff> OfferList = new List<offerStuff>();
offerStuff os = new offerStuff();
KeyValue kvOffers = tradeOffers.GetTradeOffers(get_received_offers: 1);//, active_only: 1
foreach (KeyValue kv in kvOffers["trade_offers_received"].Children)
{
os.tradeofferid = kv["tradeofferid"].AsInteger(); ;
os.accountid_other = Convert.ToUInt64(kv["accountid_other"].AsInteger());
os.message = kv["message"].AsString();
os.trade_offer_state = kv["trade_offer_state"].AsInteger();
foreach (KeyValue kv2 in kv["items_to_receive"].Children)
{
itemsClass item = new itemsClass();
item.appid = (kv2["appid"].AsInteger());
item.assetid = kv2["assetid"].AsInteger();
item.classid = kv2["classid"].AsInteger();
item.instanceid = kv2["instanceid"].AsInteger();
item.amount = kv2["amount"].AsInteger();
item.missing = kv2["missing"].AsInteger();
os.items.Add(item);
}
os.is_our_offer = kv["is_our_offer"].AsBoolean();
os.time_created = kv["time_created"].AsInteger();
os.time_updated = kv["time_updated"].AsInteger();
OfferList.Add(os);
}
return OfferList;
}
}
}
public class offerStuff
{
public int tradeofferid { get; set; }
public SteamID accountid_other { get; set; }
public string message { get; set; }
public int trade_offer_state { get; set; }
public List<itemsClass> items { get; set; }
public bool is_our_offer { get; set; }
public int time_created { get; set; }
public int time_updated { get; set; }
}
public class itemsClass
{
public int appid { get; set; }
public int assetid { get; set; }
public int classid { get; set; }
public int instanceid { get; set; }
public int amount { get; set; }
public int missing { get; set; }
}
The problem is probably that you're not initializing the collection items. You could do it on your contructor like this
public offerStuff()
{
items = new List<itemsClass>();
}
Im new in developing windows phone app --> i have problem so i have tried all the possible solutions but with no vain:-
the application tried to take result from webservice the result come back like this:-
{"d":"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"LastTickTime\":\"\/Date(1396613678728)\/\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}"}
so i have tried to parse it but it give me errors after that i have tried locally removed the {"d":" and \"LastTickTime\":\"\/Date(1396613678728)\/\" from the string with no connection to webservice and its working fine i use this code :-
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
//Json classes
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public string UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var jsonString =
"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":-579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
RootObject jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
MessageBox.Show("hello " + jsonObject.Username + "" + jsonObject.UserId);
int val1 = Convert.ToInt16(jsonObject.UserId);
if (val1 > 0)
MessageBox.Show("You are logedin");
else
{
MessageBox.Show("Sorry Please login");
}
}
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
}
Please help me to parse all of the json result (locally i mean without conection to web)and what is the code to do that.
thank you all
First, your JSON is all a string property of "D". You can't deserialize it to RootClass. Second, your JSON contains invalid escape characters in the LastTickTime area. I removed both of these, and the JSON parses without errors of any kind. I just used a console app to test it.
var s = "{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
var foo = JsonConvert.DeserializeObject<RootObject>(s);
Console.WriteLine(foo.UserId); // Writes 579
UPDATE
If you have no control over what you get back, do the following:
Take the response and get rid of the / combination. As such:
string webResponse = "your long web response from the server";
webResponse = webResponse.Replace(#"\/", "/");
// If dynamic isn't in the phone subset, you'll need a class here containing "d" as a string.
var jsonOuter = JsonConvert.DeserializeObject<dynamic>(webResponse);
var jsonInner = JsonConvert.DeserializeObject<RootObject>(jsonOuter.d);
if (jsonInner.UserId > .....)