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>
Related
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);
}
I am trying to call the Azure DevOps Release Api to create a release from c# code, but it is giving me 400 Bad request error.
I am using the example in the following link by Microsoft
https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/create?view=azure-devops-rest-5.1
Here is my code .....
My application is a small console app.
namespace DevOpsReleasePipelineTest
{
public class InstanceReference
{
public string id { get; set; }
public IList<string> name { get; set; }
public string definitionId { get; set; }
}
public class Artifacts
{
public string alias { get; set; }
public InstanceReference instanceReference { get; set; }
}
public class Application
{
public int definitionId { get; set; }
public string description { get; set; }
public IList<Artifacts> artifacts { get; set; }
public bool isDraft { get; set; }
public string reason { get; set; }
public IList<object> manualEnvironments { get; set; }
}
}
private static Application GetPayLoad()
{
InstanceReference instanceReference = new InstanceReference();
instanceReference.id = "7874";
instanceReference.name = null;
instanceReference.definitionId = "7874";
List<Artifacts> artifacts = new List<Artifacts>();
Artifacts artifacts1 = new Artifacts();
artifacts1.alias = "Mobility-Dev";
artifacts1.instanceReference = instanceReference;
artifacts.Add(artifacts1);
Application application = new Application();
application.definitionId = 4;
application.description = "Creating Sample release";
application.isDraft = false;
application.reason = "test";
application.manualEnvironments = null;
application.artifacts = artifacts;
return application;
}
public static async Task<HttpResponseMessage> PostRelease()
{
var personalaccesstoken = "djhghgtydfhfgdyuftyftdsf";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var payLoad = GetPayLoad();
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(payLoad),
Encoding.UTF8, "application/json");
Task <HttpResponseMessage> response = client.PostAsync("https://xxx-
devops.vsrm.visualstudio.com/DemoProj/_apis/release/releases?api-version=5.1", httpContent);
var result = await response;
return result;
}
Your code does not work on my side and I`ve checked the url. There is some problem %)
Try to use the url format from documentation:
POST https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=5.1
Additionally, you can check the error in your response:
var response = client.PostAsync("https://vsrm.dev.azure.com/<org>/<team_project>/_apis/release/releases?api-version=5.1", httpContent).Result;
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
string message = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(message);
}
My example:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace EventsCoreApi.Models.Entities
{
public partial class Event
{
public Event()
{
EventHasMusicGenre = new HashSet<EventHasMusicGenre>();
}
public uint EventId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[Timestamp]
public byte[] StartTime { get; set; }
[Timestamp]
public byte[] EndTime { get; set; }
public string Description { get; set; }
public string PolicyMinimumAge { get; set; }
public string PolicyDescription { get; set; }
public uint DressCodeId { get; set; }
public virtual DressCode DressCode { get; set; }
public virtual ICollection<EventHasMusicGenre> EventHasMusicGenre { get; set; }'
[HttpPost]
public async Task<ActionResult<Event>> PostEvent(EventDto eventFromClient)
{
var newEvent = new Event
{
Name = eventFromClient.Name,
StartDate = eventFromClient.StartDate,
EndDate = eventFromClient.EndDate,
StartTime = eventFromClient.StartTime,
EndTime = eventFromClient.StartTime,
Description = eventFromClient.Description,
DressCodeId = eventFromClient.DressCodeId,
PolicyMinimumAge = eventFromClient.PolicyMinimumAge,
PolicyDescription = eventFromClient.PolicyDescription
};
_context.Event.Add(newEvent);
await _context.SaveChangesAsync();
EventHasMusicGenre music1 = new EventHasMusicGenre()
{
EventId = newEvent.EventId,
MusicGenreId = eventFromClient.MusicGenres[0].MusicGenreId
};
EventHasMusicGenre music2 = new EventHasMusicGenre()
{
EventId = newEvent.EventId,
MusicGenreId = eventFromClient.MusicGenres[1].MusicGenreId
};
await _eventHasMusicGenresRepository.PostEventHasMusicGenre(music1);
await _eventHasMusicGenresRepository.PostEventHasMusicGenre(music2);
await _context.SaveChangesAsync();
I have to create an event object who has a many to many relationship so the linking table will be eventHasMusicGenre who has it s own repo and methods is this best way to do it?
this pattern is fine, however see below for alternative:
List<EventHasMusicGenre> genres = new List<EventHasMusicGenre>();//declare list
foreach(var g in eventFromClient.MusicGenres)//loop client array
{
genres.Add(new EventHasMusicGenre(){//add to list
MusicGenreId = g.MusicGenreId
})
}
var newEvent = new Event
{
Name = eventFromClient.Name,
StartDate = eventFromClient.StartDate,
EndDate = eventFromClient.EndDate,
StartTime = eventFromClient.StartTime,
EndTime = eventFromClient.StartTime,
Description = eventFromClient.Description,
DressCodeId = eventFromClient.DressCodeId,
PolicyMinimumAge = eventFromClient.PolicyMinimumAge,
PolicyDescription = eventFromClient.PolicyDescription,
MusicGenres : [ genres ] //list as part of model, no need to worry about the id
};
This way you dont have to hardcode indices
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();
}
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