How to call function with parameters from command - mvvm

I'm trying to call command which is bindable in tapgesture...
Why TabTappedCommand doesn't do nothing...
IrrigNetPage.xaml
<StackLayout BackgroundColor="{Binding SelectedTabColor}"
x:Name="StackService">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TabTappedCommand}" CommandParameter="service"/>
</StackLayout.GestureRecognizers>
<Image Source="{Binding ServiceTabIcon}"
HorizontalOptions="Start"
VerticalOptions="Center"
WidthRequest="16"
HeightRequest="16"
Aspect="AspectFit"
x:Name="ServiceIcon"/>
<Label Text="{i18n:Translate Service}"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Start"
TextColor="{Binding SelectedTabTextColor}"
x:Name="ServiceText"/>
</StackLayout>
IrrigNetViewModel.cs
public string ServiceTabIcon { get; set; } = "services_sel.png";
public string LocationTabIcon { get; set; } = "location.png";
public string MapTabIcon { get; set; } = "location.png";
public string ListHederIcon { get; set; } = "service_irrig.png";
public ICommand TabTappedCommand { get; }
public IrrigNetViewModel()
{
TabTappedCommand = new Command((tabName) => OnTapClicked(tabName.ToString()));
}
private void OnTapClicked(string tabName)
{
string serviceBlackIcon = "services.png";
string locationWhiteIcon = "location_sel.png";
string mapWhiteIcon = "location_sel.png";
if (tabName == "service")
{
ServiceTabIcon = "services_sel.png";
LocationTabIcon = "location.png";
MapTabIcon = "location.png";
}
else if (tabName == "location")
{
ServiceTabIcon = "services.png";
LocationTabIcon = "location_sel.png";
MapTabIcon = "location.png";
}
else
{
ServiceTabIcon = "services.png";
LocationTabIcon = "location.png";
MapTabIcon = "location_sel.png";
}
}
So, point is to change icons of selected stackLayout (and back to default icons when it's unselected) but for some reason TabTappedCommand doesn't work... What I'm missing...?

Solution:
Refer to the following code
public class IrrigNetViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string serviceTabIcon = "services.png";
public string ServiceTabIcon
{
get { return serviceTabIcon; }
set
{
serviceTabIcon = value;
PropertyChanged(this, new PropertyChangedEventArgs("ServiceTabIcon"));
}
}
private string locationTabIcon = "services.png";
public string LocationTabIcon
{
get { return locationTabIcon; }
set
{
locationTabIcon = value;
PropertyChanged(this, new PropertyChangedEventArgs("LocationTabIcon"));
}
}
private string mapTabIcon = "location.png";
public string MapTabIcon
{
get { return mapTabIcon; }
set
{
mapTabIcon = value;
PropertyChanged(this, new PropertyChangedEventArgs("MapTabIcon"));
}
}
private string listHederIcon = "services.png";
public string ListHederIcon
{
get { return listHederIcon; }
set
{
listHederIcon = value;
PropertyChanged(this, new PropertyChangedEventArgs("ListHederIcon"));
}
}
public ICommand TabTappedCommand { get; }
public IrrigNetViewModel()
{
TabTappedCommand = new Command((tabName) => OnTapClicked(tabName.ToString()));
}
private void OnTapClicked(string tabName)
{
if (tabName == "service")
{
ServiceTabIcon = "location.png";
LocationTabIcon = "location.png";
MapTabIcon = "location.png";
}
else if (tabName == "location")
{
ServiceTabIcon = "services.png";
LocationTabIcon = "location_sel.png";
MapTabIcon = "location.png";
}
else
{
ServiceTabIcon = "services.png";
LocationTabIcon = "location.png";
MapTabIcon = "location_sel.png";
}
}
}

You are missing the Generic type for the Command that is required to pass a parameter.
public ICommand TabTappedCommand<string> { get; }
public IrrigNetViewModel()
{
TabTappedCommand = new Command<string>(OnTapClicked);
}

Related

Inline comparison works, but if I wrap that in a method, LINQ expression cannot be translated

Full source code is at the bottom, but here is the highlight.
//Works
if (mydb.Articles.Any(x => (x.ArticleId == demo.ArticleId && x.Title == demo.Title)))
public bool IsSame(WebArticle other)
{
return (ArticleId == other.ArticleId && Title == other.Title);
}
//Doesn't work
if (mydb.Articles.Any(x => x.IsSame(demo)))
Is there any way to avoid the repeated code of x.ArticleId == demo.ArticleId && x.Title == demo.Title and reuse one source?
Program.cs
using Microsoft.EntityFrameworkCore.Storage;
using System.Diagnostics;
namespace EntityTest
{
internal class Program
{
static void Main(string[] args)
{
var mydb = new MyDbContext();
var article1 = new Article()
{
ArticleId = 1234,
Title = "First",
};
var article2 = new Article()
{
ArticleId = 5678,
Title = "Second",
};
var article3 = new Article()
{
ArticleId = 9012,
Title = "Third",
};
mydb.Articles.AddRange(article1, article2, article3);
mydb.SaveChanges();
var demo = new WebArticle()
{
ArticleId = 5678,
Title = "Second",
};
//use inline code
if (mydb.Articles.Any(x => (x.ArticleId == demo.ArticleId && x.Title == demo.Title)))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't exist");
}
//use method
if (mydb.Articles.Any(x => x.IsSame(demo)))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't exist");
}
}
}
class WebArticle
{
public int ArticleId { get; set; }
public string Title { get; set; }
}
}
MyDbContext.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityTest
{
internal class MyDbContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("memory");
base.OnConfiguring(optionsBuilder);
}
public DbSet<Article> Articles { get; set; }
public DbSet<ArticleImage> ArticleImages { get; set; }
}
class Article
{
[Key]
public int Id { get; set; }
public int ArticleId { get; set; }
public string Title { get; set; }
public bool IsSame(WebArticle other)
{
return (ArticleId == other.ArticleId && Title == other.Title);
}
}
class ArticleImage
{
public int Id { get; set; }
public int ArticleId { get; set; }
public string Url { get; set; }
}
}
Changed the code like the following. It worked without using a third-party library.
Program.cs
//use method
//if (mydb.Articles.AsExpandable().Any(x => x.IsSame(demo)))
if (mydb.Articles.Any(Article.IsSame(demo)))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't exist");
}
MyDbContext.cs
class Article
{
[Key]
public int Id { get; set; }
public int ArticleId { get; set; }
public string Title { get; set; }
//public bool IsSame(WebArticle other)
//{
// return (ArticleId == other.ArticleId) && (Title == other.Title);
//}
public static Expression<Func<Article, bool>> IsSame(WebArticle other)
{
return current => (current.ArticleId == other.ArticleId) && (current.Title == other.Title);
}

How to insert payload data in many-to-many relationships with EF Core 5

I have this relationship between Licitadores and Ofertas
public class Licitador
{
public int Id { get; set; }
public string Nombre { get; set; }
[StringLength(maximumLength: 15)]
public string CodigoSAP { get; set; }
public List<Oferta> Ofertas { get; set; } = new List<Oferta>();
}
public class Oferta
{
[StringLength(maximumLength:6)]
public string Id { get; set; }
[StringLength(maximumLength: 5)]
public string IdPresentada { get; set; }
....
public List<Licitador> Licitadores { get; set; } = new List<Licitador>();
}
And the join table in the context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LicitacionesEnSolitario>().ToTable("LicitacionesSolitario");
modelBuilder.Entity<Licitador>()
.HasMany(o => o.Ofertas)
.WithMany(of => of.Licitadores)
.UsingEntity<LicitacionesEnSolitario>
(oo => oo.HasOne<Oferta>().WithMany(),
oo => oo.HasOne<Licitador>().WithMany())
.Property(oo => oo.Adjudicado)
.IsRequired();
}
I need this data in my entity/table LicitacionesEnSolitario in addition to PK y FK
public class LicitacionesEnSolitario
{
public int LicitadorId { get; set; }
public string OfertaId { get; set; }
public bool Adjudicado { get; set; }
public string Plazo { get; set; }
public decimal PresupuestoOfertado { get; set; }
public DateTime? FechaAdjudicacion { get; set; }
}
Here I insert the data importing them from another database
public int ImportarLicitacionesEnSolitario()
{
try
{
int registrosAñadidos = 0;
var registrosSAP = _contextSAP.LicitacionesEnSolitario
.FromSqlRaw("sql")
.ToList();
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
oferta.Licitadores.Add(licitador);
registrosAñadidos +=1;
}
_contextBoletus.SaveChanges();
return registrosAñadidos;
}
catch (Exception ex)
{
throw ex;
}
}
This works fine and insert data in "LicitacionesEnSolitario" but with this fields Adjudicado, Plazo, PresupuestoPfertado y FechaAdjudicacion with nulls.
I don't know how to insert them at the time I insert Licitadores and if I try to update after the Add method using the PKs I just added
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
oferta.Licitadores.Add(licitador);
var ls = _contextBoletus.Set<LicitacionesEnSolitario>()
.SingleOrDefault(ls => ls.OfertaId == oferta.Id & ls.LicitadorId == licitador.Id);
ls.Adjudicado = registroSAP.Adjudicado;
ls.PresupuestoOfertado = registroSAP.PresupuestoOfertado;
ls.FechaAdjudicacion = registroSAP.FechaAdjudicacion;
registrosAñadidos +=1;
}
_contextBoletus.SaveChanges();
return registrosAñadidos;
I get this error System.NullReferenceException: Object reference not set to an instance of an object.
Any idea, please?
Thanks
This is the best way I found
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
var ls = _contextBoletus.Set<LicitacionesEnSolitario>().Add(
new LicitacionesEnSolitario
{
LicitadorId = licitador.Id,
OfertaId = oferta.Id,
Adjudicado = registroSAP.Adjudicado,
Plazo = registroSAP.Plazo,
PresupuestoOfertado = registroSAP.PresupuestoOfertado,
FechaAdjudicacion = registroSAP.FechaAdjudicacion
});
registrosAñadidos += 1;
}
Thanks

How to consume an external api rest?

I need to consume a Rest API from an ERP Site, where I will list some items from this site, but I do not find anything useful that can help me to consume
I am using json and http client to perform, but the error in the process recognize the site path
public partial class ProdutoPage : ContentPage
{
ListView lv = new ListView();
public ProdutoPage()
{
InitializeComponent();
iniciar();
}
private async void iniciar()
{
//tinyapp API = new tinyapp();
//var lista = API.ListaCategorias("automacao");
var client = new HttpClient();
client.DefaultRequestHeaders.Add("token", "");
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/pedidos.pesquisa.php/");
var resp = await client.GetAsync("pedidos.pesquisa.php/");
if (resp.IsSuccessStatusCode)
{
var respStr = await resp.Content.ReadAsStringAsync();
var l = JsonConvert.DeserializeObject<List<Pedido>>(respStr);
lv.ItemsSource = l;
}
}
}
}
I need a list of ERP site requests
in ASP.Net has no error, but in xamarim it does not have the using System.Web.Script.Serialization to enable javascript
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml.Linq;
namespace mia.Webservices
{
public class TinyAPI
{
private const string URL_PEDIDOS = "https://api.tiny.com.br/api2/pedidos.pesquisa.php/";
private const string URL_OBTER_PEDIDO = "https://api.tiny.com.br/api2/pedido.obter.php/";
private string parametros = "?formato=json";
private string token_solucoes = "";
private string token_automacao = "";
/// <summary>
/// ListaPedidos é um método que lista todos os pedidos do Tiny de acordo com os parâmetros data inicial e data final.
/// </summary>
public List<Pedido> ListaPedidos(string empresa, string situacao, string data_inicial, string data_final)
{
int pagina = 1;
string token = "";
if (empresa.Equals("automacao"))
{
token = token_automacao;
}
else
{
if (empresa.Equals("solucoes"))
{
token = token_solucoes;
}
}
HttpClient client = new HttpClient();
var baseAddress = new Uri(URL_PEDIDOS);
client.BaseAddress = baseAddress;
List<Pedido> pedidos = new List<Pedido>();
HttpResponseMessage response = null;
if (data_inicial != null && data_inicial != "" && data_final != null && data_final != "")
{
response = client.GetAsync(parametros + "&token=" + token + "&dataInicial=" + data_inicial + "&dataFinal=" + data_final + "&situacao=" + situacao).Result;
}
else
{
response = client.GetAsync(parametros + "&pagina=" + pagina + "&token=" + token).Result;
}
string json = response.Content.ReadAsStringAsync().Result;
Dictionary<string, object> userObject = new JavaScriptSerializer().DeserializeObject(json) as Dictionary<string, object>;
if (userObject.ContainsKey("retorno"))
{
Object meta = userObject["retorno"];
Dictionary<string, object> dic_meta = (Dictionary<string, object>)meta;
if (dic_meta.ContainsKey("numero_paginas"))
{
int total_count = (int)dic_meta["numero_paginas"];
while (total_count >= pagina)
{
HttpResponseMessage response_2 = null;
if (data_inicial != null && data_inicial != "" && data_final != null && data_final != "")
{
response_2 = client.GetAsync(parametros + "&token=" + token + "&dataInicial=" + data_inicial + "&dataFinal=" + data_final + "&situacao=" + situacao).Result;
}
else
{
response_2 = client.GetAsync(parametros + "&pagina=" + pagina + "&token=" + token).Result;
}
string json_2 = response_2.Content.ReadAsStringAsync().Result;
Dictionary<string, object> userObject_2 = new JavaScriptSerializer().DeserializeObject(json_2) as Dictionary<string, object>;
Dictionary<string, object> objetos = (Dictionary<string, object>)userObject_2["retorno"];
if (objetos.ContainsKey("pedidos"))
{
Object[] pedidos_list = (Object[])objetos["pedidos"];
foreach (var item in pedidos_list)
{
Dictionary<string, object> pre_lista_pedidos = (Dictionary<string, object>)item;
Dictionary<string, object> list_pedidos = (Dictionary<string, object>)pre_lista_pedidos["pedido"];
Pedido pedido = new Pedido();
pedido.situacao = (string)list_pedidos["situacao"];
pedido.id = (string)list_pedidos["id"];
pedido.numero = (string)list_pedidos["numero"];
pedido.numero_ecommerce = (string)list_pedidos["numero_ecommerce"];
pedido.data_pedido = (string)list_pedidos["data_pedido"];
pedido.data_prevista = (string)list_pedidos["data_prevista"];
pedido.nome = (string)list_pedidos["nome"];
pedido.valor = (string)list_pedidos["valor"].ToString();
pedido.id_vendedor = (string)list_pedidos["id_vendedor"];
pedido.nome_vendedor = (string)list_pedidos["nome_vendedor"];
pedido.codigo_rastreamento = (string)list_pedidos["codigo_rastreamento"];
pedido.url_rastreamento = (string)list_pedidos["url_rastreamento"];
pedidos.Add(pedido);
}
}
total_count -= 1;
}
}
}
return pedidos;
}
}
This works:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("token", "0dbffc6cbb412c01a90431f07631c0e00f2889d4");
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/");
var resp = client.GetAsync("pedidos.pesquisa.php").GetAwaiter().GetResult();
After a research I discovered your API requires POST to return data:
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/");
var parameters = new Dictionary<string, string> { { "token", "0dbffc6cbb412c01a90431f07631c0e00f2889d4" } };
var encodedContent = new FormUrlEncodedContent(parameters);
var resp = await client.PostAsync("pedidos.pesquisa.php", encodedContent);
var respStr = await resp.Content.ReadAsStringAsync();
> var client = new HttpClient();
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/");
var resp = client.GetAsync("pedidos.pesquisa.php?token=********&formato=json").Result;
if (resp.IsSuccessStatusCode)
{
var respStr = resp.Content.ReadAsStringAsync().Result;
var l = JsonConvert.DeserializeObject<List<Pedido>>(respStr);
lv.ItemsSource = l;
}`
doing so he located the token, but an error in Json, follows an example of json from the Pedido list
{
"retorno": {
"status_processamento": 3,
"status": "OK",
"pagina": "1",
"numero_paginas": "1",
"pedidos": [
{
"pedido": {
"id": 123456,
"numero": 123456,
"numero_ecommerce": "12",
"data_pedido": "01/01/2013",
"data_prevista": "10/01/2013",
"nome": "Cliente Teste",
"valor": "100.25",
"id_vendedor": "123456",
"nome_vendedor": "Vendedor Teste",
"situacao": "Atendido"
}
},
{
"pedido": {
"id": 123456,
"numero": 123458,
"numero_ecommerce": "15",
"data_pedido": "01/01/2013",
"data_prevista": "10/01/2013",
"nome": "Cliente Teste 3",
"valor": "50.25",
"id_vendedor": "",
"nome_vendedor": "",
"situacao": "Aberto"
}
}
]
}
}
error Newtonsoft.Json.JsonSerializationException:
pedido class
public class Pedido
{
public string id { get; set; }
public string numero { get; set; }
public string numero_ecommerce { get; set; }
public string data_pedido { get; set; }
public string data_prevista { get; set; }
public string nome { get; set; }
public string valor { get; set; }
public string id_vendedor { get; set; }
public string nome_vendedor { get; set; }
public string situacao { get; set; }
public string codigo_rastreamento { get; set; }
public string url_rastreamento { get; set; }
public string data_faturamento { get; set; }
public Cliente cliente { get; set; }
public List<Produto_Servico> produtos_servicos { get; set; }
}
Class Pedidos
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace MacVendas.Models.API
{
public class Pedido
{
public class Pedido2
{
public string id { get; set; }
public string numero { get; set; }
public string numero_ecommerce { get; set; }
public string data_pedido { get; set; }
public string data_prevista { get; set; }
public string nome { get; set; }
public string valor { get; set; }
public string id_vendedor { get; set; }
public string nome_vendedor { get; set; }
public string situacao { get; set; }
public string codigo_rastreamento { get; set; }
public string url_rastreamento { get; set; }
}
public class Pedido1
{
public string pedido { get; set; }
}
public class Retorno
{
public string status_processamento { get; set; }
public string status { get; set; }
public string pagina { get; set; }
public string numero_paginas { get; set; }
public List<Pedido1> pedidos { get; set; }
}
public class RootObject
{
public Retorno retorno { get; set; }
}
}
}
I was able to read the list of categories that is smaller
using System;
using System.Collections.Generic;
using System.Text;
namespace MacVendas.Models.API
{
public class Categoria
{
public class Retorno
{
public string id { get; set; }
public string descricao { get; set; }
public List<object> nodes { get; set; }
}
public class RootObject
{
public List<Retorno> retorno { get; set; }
}
}
}
Produtopagexaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using MacVendas.Classes;
//using macvendas.services;
using MacVendas.Models.API;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MacVendas.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ProdutoPage : ContentPage
{
public ProdutoPage()
{
InitializeComponent();
Iniciar();
}
private void Iniciar()
{
var client = new HttpClient();
var resp = client.GetAsync("https://api.tiny.com.br/api2/produtos.categorias.arvore.php?token=*****&formato=json").Result;
string respStr = resp.Content.ReadAsStringAsync().Result;
Categoria.RootObject ObjPedidotList = new Categoria.RootObject ();
if (respStr != "")
{
ObjPedidotList = JsonConvert.DeserializeObject<Categoria.RootObject>(respStr);
}
//Binding listview with server response
listviewConacts.ItemsSource = ObjPedidotList.retorno;
}
}
}
produto.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="MacVendas.Pages.ProdutoPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Margin="10" Text="JSON Parsing" FontSize="25" />
<ListView x:Name="listviewConacts" Grid.Row="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand" Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Text="{Binding descricao}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue" FontAttributes="Bold"/>
<!--<Label Text="{Binding numero}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange" FontAttributes="Bold"/>
<Label Text="{Binding valor}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray" FontAttributes="Bold"/>-->
<BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="FillAndExpand" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>

How to implement Expandable ListView in xamarin forms

I'm using service to get some values from json.
I displaying them on home page (IrrigNetPage) where I have three tabs, so I want to sort them on diferents way on every tab.
Here's my model:
public class IrrigNetModel
{
public IrrigNetModelItem[] items { get; set; }
}
public class IrrigNetModelItem
{
public int ID { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public string DateText { get; set; }
public int StationId { get; set; }
public string StationName { get; set; }
public float StationLongitude { get; set; }
public float StationLatitude { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
}
Here's a part of xaml code from View:
<StackLayout
Grid.Column="1"
Orientation="Horizontal"
HorizontalOptions="FillAndExpand"
BackgroundColor="{Binding LocationTabColor}"
Padding="10"
Margin="1">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TabTappedCommand}" CommandParameter="location"/>
</StackLayout.GestureRecognizers>
<Image Source="{Binding LocationTabIcon}"
HorizontalOptions="Start"
VerticalOptions="Center"
WidthRequest="16"
HeightRequest="16"
Aspect="AspectFit"
x:Name="LocationIcon"/>
<Label Text="{i18n:Translate Location}"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Start"
TextColor="{Binding LocationTabTextColor}"/>
</StackLayout>
And, ofcourse here is part of ViewModel:
else if (tabName == "location")
{
ServiceTabColor = Color.FromHex("#f4f4f4");
LocationTabColor = Colors.MENU_SELECTED_ITEM;
MapTabColor = Color.FromHex("#f4f4f4");
ServiceTabIcon = "services.png";
LocationTabIcon = "location_sel.png";
MapTabIcon = "location.png";
ServiceTabTextColor = Colors.MENU_SELECTED_ITEM;
LocationTabTextColor = Color.FromHex("#ffffff");
MapTabTextColor = Colors.MENU_SELECTED_ITEM;
ListHederIcon = "location.png";
IsListVisible = IsListVisible;
IsGridHeaderVisible = true;
IsMapVisible = false;
if (ServiceName == "irrigNET")
{
FrameIcon = "service_irrig.png";
}
else
{
FrameIcon = "service_trap.png";
}
GroupServicesByLocation();
}
Where I set some proporties values and as you can see here I call method GroupServicesByLocation(); which looks like:
public void GroupServicesByLocation()
{
var groupedCollection = IrrigNetCollection.GroupBy(x => x.StationName);
}
public ObservableCollection<IrrigNetModelItem> IrrigNetCollection { get; set; } = new ObservableCollection<IrrigNetModelItem>();
public async void GetData()
{
base.OnAppearing();
dialog.Show();
var token = LocalData.Token;
var data = await IrrigNetService.GetServices(token, "sr");
var irrigNetModel = new IrrigNetModelItem();
foreach (var d in data.items)
{
IrrigNetCollection.Add(d);
if (d.ServiceName == "irrigNET")
{
IrrigCounter++;
FrameImage = "service_irrig_img.png";
FrameHeaderColor = Color.FromHex("#33A8F7");
ServiceName = "irrigNET";
FrameIcon = "service_irrig.png";
}
else
{
AlertCounter++;
FrameImage = "alert.png";
FrameHeaderColor = Color.FromHex("#2BB24B");
ServiceName = "alertNET";
FrameIcon = "service_trap.png";
}
}
dialog.Hide();
}

HttpClient.PostAsJsonAsync can`t Serialize inherited property

my code is
public class BaseDTO
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
public class DataDTO : BaseDTO
{
public int Level { get; set; }
public DateTime ChangedDate { get; set; }
}
I call web-api by httpclient
static void Main(string[] args)
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.UseDefaultCredentials = true;
var client = new HttpClient(httpClientHandler);
client.BaseAddress = new Uri("http://localhost/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var dto = new DataDTO()
{
Id = 1,
Code = "a",
Name = "A",
Level = 10,
ChangedDate = DateTime.Now
};
HttpResponseMessage resp =
client.PostAsJsonAsync(
"api/MyApi/Creat", dto).Result;
if (resp.IsSuccessStatusCode)
{
}
}
when i debug,i found the data that server received ,"Id","Code" and "Name" inherited from base class were all null,"Level" and "ChangedDate" were right.
I googled,but I cannot find my reason.
changed to use restsharp,it works well