Why I can't parse string array from JSON - webapi

I was writing a code for exchange app using my local bank api.
JSON response looks like this:
{"date":"01.12.2014",
"bank":"PB",
"baseCurrency":980,
"baseCurrencyLit":"UAH",
"exchangeRate[{"baseCurrency":"UAH","currency":"AUD","saleRateNB":12.8319250,"purchaseRateNB":12.8319250,{"baseCurrency":"UAH","currency":"CAD","saleRateNB":13.2107400,"purchaseRateNB":13.2107400,"saleRate":15.0000000,"purchaseRate":13.0000000},
*other currencies here in exchangeRate array*}]
I am using this approach
private static async Task ProcessExchangeRate()
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var responce = await client.GetAsync("https://api.privatbank.ua/p24api/exchange_rates?json&date=01.12.2020");
if (responce.IsSuccessStatusCode)
{
ExchangeRate rate = await responce.Content.ReadAsAsync<ExchangeRate>();
}
}
ExchangeRate class
[JsonPropertyName("date")]
public string Date { get; set; }
[JsonPropertyName("exchangeRate")]
public string Rates { get; set; }
For some reason it works for Date property, but not for Rates. What should I do?

I found out, that I should have use
public object[] exchangeRate { get; set; }
for exchangeRate, thx #Kerem for pointing me on it.

Related

Storing server timestamp in a variable [duplicate]

Trying to get the server timestamp at the CreatedAt document field before the document is added to the cloud. So it could be applied to the Time property and also saved locally, However this is what I get:
My ChatTestMessageGroup Model
public class ChatTestMessageGroup : TimeTest
{
public long MessageId { get; set; }
public string Message { get; set; }
public string Time { get; set; }
}
public class TimeTest
{
[ServerTimestamp]
public Timestamp CreatedAt { get; set; }
public Timestamp StampAt { get; set; }
}
Send Message Execution code
private async Task SendTestMessageAsync()
{
if (string.IsNullOrWhiteSpace(Message)) return;
// under testing.
var test = new ChatTestMessageGroup()
{
MessageId = new Timestamp().ToDateTime().Ticks,
Message = Message.Trim(),
};
test.Time = $"{test.CreatedAt.ToDateTime():HH:mm}";
await CloudService.CS.SendMessageAsync(test);
Message = "";
}
Write To Cloud Code
public async Task SendMessageAsync(ChatTestMessageGroup testMessage)
{
IDocumentReference doc = CrossCloudFirestore.Current.Instance.Collection("Testing").Document(DateTime.Now.Day.ToString());
await doc.Collection("Tester").Document(${testMessage.CreatedAt.Seconds}").SetAsync(testMessage);
}
The plugin I'm using
Plugin.CloudFirestore
Trying to get the server timestamp at the CreatedAt document field before the document is added to the cloud.
This is not possible. The time is taken at the server the moment the document is created. The client app can't be certain what the time is on the server because its own clock could be wrong. You can only get the timestamp that was written by reading the document back.

DateTime? to DateTime

I am stuck. I'm creating a database of authors and run to a problem. I need to save value Umrti (date of death) to database as null, but it always save that value as 01.01.0001. I tried few things and now my code looks like this:
public class AutorDetailModel
{
public int Id { get; set; }
[Required]
public string Jmeno { get; set; }
[Required]
public string Prijmeni { get; set; }
public string ProstredniJmeno { get; set; }
[DotvvmEnforceClientFormat]
public DateTime Narozeni { get; set; }
[DotvvmEnforceClientFormat]
public DateTime? Umrti { get; set; }
public string Bio { get; set; }
public string Narodnost { get; set; }
public byte Obrazek { get; set; }
}
And in service like this:
public async Task UpdateAutorAsync(AutorDetailModel autor)
{
using (var dbContext = CreateDbContext())
{
var entity = await dbContext.Autors.FirstOrDefaultAsync(s => s.Id == autor.Id);
entity.Jmeno = autor.Jmeno;
entity.Prijmeni = autor.Prijmeni;
entity.ProstredniJmeno = autor.ProstredniJmeno;
entity.Narozeni = autor.Narozeni;
entity.Umrti = autor.Umrti;
entity.Bio = autor.Bio;
entity.Narodnost = autor.Narodnost;
entity.Obrazek = autor.Obrazek;
await dbContext.SaveChangesAsync();
}
}
However, autor.Umrti still gives me this error:
Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)
I am really stuck and will appreciate any advice. Thanks
And sorry for my bad english :)
you must check Umrti is null or not
public async Task UpdateAutorAsync(AutorDetailModel autor)
{
using (var dbContext = CreateDbContext())
{
var entity = await dbContext.Autors.FirstOrDefaultAsync(s => s.Id == autor.Id);
entity.Jmeno = autor.Jmeno;
entity.Prijmeni = autor.Prijmeni;
entity.ProstredniJmeno = autor.ProstredniJmeno;
entity.Narozeni = autor.Narozeni;
if(autor.Umrti!=null)
entity.Umrti = autor.Umrti;
entity.Bio = autor.Bio;
entity.Narodnost = autor.Narodnost;
entity.Obrazek = autor.Obrazek;
await dbContext.SaveChangesAsync();
}
}
If you're using SQL Server (possibly other Database engines too) then you can't save a NULL value in a DateTime field.
You'll have to convert the NULL to a date, any date, to save it in the db. Typically SQL Server uses '1900-01-01' to represent a NULL date. In most cases that's fine as, unless you are working with historical data around the end of the 18th Century, it won't clash with your valid data. When reading from the db you can convert all dates with a value of '1900-01-01' to null in your code, and when writing to the db if the value in code is null convert it to '1900-01-01'.

Serializing a BsonArray with C# driver

Problem: I have a Mongo document that includes two arrays. One of the arrays is large, with subdocuments. This one serializes with no problem. Another is a simple array of this type:
staffgroups {"Tech","Sales"}
This one will not serialize. I get errors saying it's a BsonArray. The closest I've been able to get to serializing it produces a string. I need a JSON object.
Code time:
public class specialtyGroup
{
public ObjectId _id { get; set; }
public string name { get; set; }
public string location { get; set; }
public coachConfig config { get; set; }
public schedules[] coaches { get; set; }
public BsonArray staffgroups { get; set; }
}
And the webservice:
public void GetGroups()
{
var client = new MongoClient();
var db = client.GetDatabase("MongoTul");
var coll = db.GetCollection<specialtyGroup>("specialtyGroups");
string cname = HttpContext.Current.Request.Params["loc"];
var creatures = coll.Find(b => b.location == cname)
.ToListAsync()
.Result;
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(creatures));
}
I've tried using aggregation and projecting. I've tried creating an additional class for staffgroups (which works for my complex array). And a few other things. All no good.
Most common error looks like this: Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonBoolean'.
I spent hours on this before posting here, then after posting I figured it out in 30 mins. Sorry.
The answer is staffgroups should be "public string[] staffgroups {get; set;}
So if any other rubes like me have that question, there's the answer.

ASP .NET Web API SaveChangesAsync with Foreign Key Data

I have Customer and Address classes, something like this:
public class Customer
{
[PrimaryKey]
public int Id { get; set; }
public string CustomerName { get; set; }
public int ShippingAddressId { get; set; }
[ForeignKey("ShippingAddressId")]
public Address ShippingAddress { get; set; }
}
public class Address
{
[PrimaryKey]
public int Id { get; set; }
public string City { get; set; }
}
When I call a Web API to update the Customer, I pass an edited Customer object to this method. For example, I edit 2 properties: Customer.CustomerName and Customer.ShippingAddress.City
AuthenticationResult ar = await new AuthHelper().AcquireTokenSilentAsync();
if (ar.Token == null) return false;
using (var json = new StringContent(JsonConvert.SerializeObject(entity), UnicodeEncoding.UTF8, "application/json"))
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(Settings.ApiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ar.Token);
using (HttpResponseMessage response = await client.PutAsync("api/" + type.ToString() + "/" + id, json))
{
response.EnsureSuccessStatusCode();
return await InsertOrReplaceResponse(type, response);
}
}
Here is the Web API:
[HttpPut("{id}")]
public async Task<IActionResult> PutCustomer([FromRoute] int id, [FromBody] Customer customer)
{
_context.Entry(customer).State = EntityState.Modified;
await _context.SaveChangesAsync();
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
However, only Customer.CustomerName gets updated. The foreign key data (Customer.ShippingAddress.City) isn't updated in the Address table.
Any idea what I'm doing wrong?
Thanks!
Generally, I would expect the child Address entity to be update as well because you use foreign key association which also should be the default for one-to-one mappings (see here for more details). However, it seems that something is not setup right and you get independent association behavior where you have to manage child entity state yourself. Should be a simple fix in your case:
_context.Entry(customer).State = EntityState.Modified;
_context.Entry(customer.ShippingAddress).State = EntityState.Modified;

WebAPI Serialization problems when consuming Recurly Rest API which returns XML

I'm new to the ASP.Net Web API. I'm trying to interact with the Recurly REST based API and I am getting errors like below during my ReadAsAsync call which is the point I believe it attempts to serialize the response.
{"Error in line 1 position 73. Expecting element 'account' from namespace 'http://schemas.datacontract.org/2004/07/RecurlyWebApi.Recurly'.. Encountered 'Element' with name 'account', namespace ''. "}
Here is my HttpClient implementation, simplified for brevity:
public class RecurlyClient
{
readonly HttpClient client = new HttpClient();
public RecurlyClient()
{
var config = (RecurlySection)ConfigurationManager.GetSection("recurly");
client.BaseAddress = new Uri(string.Format("https://{0}.recurly.com/v2/", config.Subdomain));
// Add the authentication header
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(config.ApiKey)));
// Add an Accept header for XML format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
}
public T Get<T>(string id)
{
var accounts = default(T);
// Make the request and get the response from the service
HttpResponseMessage response = client.GetAsync(string.Concat("accounts/", id)).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
accounts = response.Content.ReadAsAsync<T>().Result;
}
return accounts;
}
}
And here is my model:
[XmlRoot("account")]
public class Account
{
[XmlAttribute("href")]
public string Href { get; set; }
[XmlElement("account_code")]
public string AccountCode { get; set; }
[XmlElement("state")]
public AccountState State { get; set; }
[XmlElement("username")]
public string Username { get; set; }
[XmlElement("email")]
public string Email { get; set; }
[XmlElement("first_name")]
public string FirstName { get; set; }
[XmlElement("last_name")]
public string LastName { get; set; }
[XmlElement("company_name")]
public string Company { get; set; }
[XmlElement("accept_language")]
public string LanguageCode { get; set; }
[XmlElement("hosted_login_token")]
public string HostedLoginToken { get; set; }
[XmlElement("created_at")]
public DateTime CreatedDate { get; set; }
[XmlElement("address")]
public Address Address { get; set; }
}
And an example of the XML response from the service:
<account href="https://mysubdomain.recurly.com/v2/accounts/SDTEST01">
<adjustments href="https://mysubdomain.recurly.com/v2/accounts/SDTEST01/adjustments"/>
<invoices href="https://mysubdomain.recurly.com/v2/accounts/SDTEST01/invoices"/>
<subscriptions href="https://mysubdomain.recurly.com/v2/accounts/SDTEST01/subscriptions"/>
<transactions href="https://mysubdomain.recurly.com/v2/accounts/SDTEST01/transactions"/>
<account_code>SDTEST01</account_code>
<state>active</state>
<username>myusername</username>
<email>simon#example.co.uk</email>
<first_name>First name</first_name>
<last_name>Last name</last_name>
<company_name>My Company Name</company_name>
<vat_number nil="nil"></vat_number>
<address>
<address1>My Address Line 1/address1>
<address2>My Address Line 2</address2>
<city>My City</city>
<state>My State</state>
<zip>PL7 1AB</zip>
<country>GB</country>
<phone>0123456789</phone>
</address>
<accept_language nil="nil"></accept_language>
<hosted_login_token>***</hosted_login_token>
<created_at type="datetime">2013-08-22T15:58:17Z</created_at>
</account>
I think the problem is because by default the DataContractSerializer is being used to deserialize the XML, and by default the DataContractSerializer uses a namespace of namespace http://schemas.datacontract.org/2004/07/Clr.Namespace. (In this case Clr.Namepace is RecurlyWebApi.Recurly.)
Because your XML has attributes, you need to use the XmlSerializer instead of the DataContractSerializer, and you're set up to do this because your account class is decorated with Xml* attributes. However, you have to use an XmlMediaTypeFormatter which is using the XmlSerializer. You can do this by setting a flag on the global XMLFormatter as described on this page:
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;
or by supplying a MediaTypeFormatter as a parameter to your ReadAsAsync call:
var xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xmlFormatter.UseXmlSerializer = true;
accounts = response.ReadAsAsync<T>(xmlFormatter).Result
Not 100% sure of this because this doesn't explain why the first 'account' in your error message is lower case - the DataContractSerializer should ignore the XmlRoot attribute.

Resources