I am trying to call the EORI validation open interface from within a C# application but am not getting anywhere.
I've looked around the site and there doesn't seem to be any documentation on how to do this.
Site: http://ec.europa.eu/taxation_customs/dds2/eos/news/newstar.jsp?Lang=en
WSDL: http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation?wsdl
I've created a new C# Console App and added the WSDL as a service reference then tried calling the service but get the following exception...
System.ServiceModel.CommunicationException: 'The server did not
provide a meaningful reply; this might be caused by a contract
mismatch, a premature session shutdown or an internal server error.'
I've used the online tool with the number and it returns data as expected
http://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=en
Has anybody else had any luck with this?
Thanks
Thanks for the help, In case anyone else was struggling, below is the helper class for making and sending the request.
public class EoriModel
{
string _url;
public EoriModel()
{
_url = "http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation";
}
public EoriResponseModel ValidateEoriNumber(string number)
{
if (number == null)
{
return null;
}
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(number);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
string response;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
response = rd.ReadToEnd();
}
}
int startPos = response.IndexOf("<return>");
int lastPos = response.LastIndexOf("</return>") - startPos + 9;
string responseFormatted = response.Substring(startPos, lastPos);
XmlSerializer serializer = new XmlSerializer(typeof(EoriResponseModel));
EoriResponseModel result;
using (TextReader reader = new StringReader(responseFormatted))
{
result = (EoriResponseModel)serializer.Deserialize(reader);
}
return result;
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string number)
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.AppendFormat("<soap:Envelope xmlns:soap={0} >", "'http://schemas.xmlsoap.org/soap/envelope/'");
xmlBuilder.Append("<soap:Body>");
xmlBuilder.AppendFormat("<ev:validateEORI xmlns:ev={0} >", "'http://eori.ws.eos.dds.s/'");
xmlBuilder.AppendFormat("<ev:eori>{0}</ev:eori>", number);
xmlBuilder.Append("</ev:validateEORI>");
xmlBuilder.Append("</soap:Body> ");
xmlBuilder.Append("</soap:Envelope> ");
soapEnvelopeDocument.LoadXml(xmlBuilder.ToString());
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
And the class with annotation used to parse the results
[XmlRoot(ElementName = "return")]
public class EoriResponseModel
{
[XmlElement(ElementName = "requestDate")]
public string RequestDate { get; set; }
[XmlElement(ElementName = "result")]
public List<Result> Result { get; set; }
}
[XmlRoot(ElementName = "result")]
public class Result
{
[XmlElement(ElementName = "eori")]
public string Eori { get; set; }
[XmlElement(ElementName = "status")]
public string Status { get; set; }
[XmlElement(ElementName = "statusDescr")]
public string StatusDescr { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "street")]
public string Street { get; set; }
[XmlElement(ElementName = "postalCode")]
public string PostalCode { get; set; }
[XmlElement(ElementName = "city")]
public string City { get; set; }
[XmlElement(ElementName = "country")]
public string Country { get; set; }
}
If you Google the URI that is deep in the Reference.cs file that opens if you open the definition of the EORI validation methods, then you'll that someone on this page here https://www.codeproject.com/Questions/1075553/Soap-Message-Format-Issue-while-accessing-webservi is having the same issue.
On that page he quotes this sample code that he is using to make a query.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ev:validateEORI xmlns:ev="http://eori.ws.eos.dds.s/">
<ev:eori>DE123456</ev:eori>
<ev:eori>IT123456789</ev:eori>
</ev:validateEORI>
</soap:Body>
</soap:Envelope>
Try this code in Postman, and enjoy the results. :D
His query is ultimately that the C# code he wrote isn't creating valid XML, but at least this XML will get you results from the API for your testing / development process to proceed.
Related
I want to get all variables from https://api.coinmarketcap.com/v1/ticker/ in my c# console application.
How can I do this?
I started with getting the whole page as a stream. What to do now?
private static void start_get()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create
(string.Format("https://api.coinmarketcap.com/v1/ticker/"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
Console.WriteLine(_Answer.ReadToEnd());
}
First you need a custom class to use for deserialization:
public class Item
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
[JsonProperty(PropertyName = "24h_volume_usd")] //since in c# variable names cannot begin with a number, you will need to use an alternate name to deserialize
public string volume_usd_24h { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
Next, you can use Newtonsoft Json, a free JSON serialization and deserialization framework in the following way to get your items (include the following using statements):
using System.Net;
using System.IO;
using Newtonsoft.Json;
private static void start_get()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://api.coinmarketcap.com/v1/ticker/"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
string jsonString;
using (Stream stream = WebResp.GetResponseStream()) //modified from your code since the using statement disposes the stream automatically when done
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(jsonString);
Console.WriteLine(items.Count); //returns 921, the number of items on that page
}
Finally, the list of elements is stored in items.
A simplified version of Keyur PATEL's work.
static void GetCoinValues()
{
string json = new WebClient().DownloadString("https://api.coinmarketcap.com/v1/ticker/");
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (var item in items)
{
Console.WriteLine("ID: " + item.id.ToUpper());
Console.WriteLine("Name: " + item.name.ToUpper());
Console.WriteLine("Symbol: " + item.symbol.ToUpper());
Console.WriteLine("Rank: " + item.rank.ToUpper());
Console.WriteLine("Price (USD): " + item.price_usd.ToUpper());
Console.WriteLine("\n");
}
}
I have a service that is posting data to a URL and listening for the response.
This is the service call
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, encode, true);
string strResponse = reader.ReadToEnd();
The string response that it's returning is
"{"TransactionConfirmationWrapedResult":"{\"ResultCode\":\"1\",\"ResultDesc\":\"Failed -\",\"ThirdPartyTransID\":\"\"}"}"
I would like to map this result to class like this;
public class M2PDto
{
[DataMember(Name = "TransactionConfirmationWrapedResult")]
public M2P2Dto WrapedResult { get; set; }
}
public class M2P2Dto
{
[DataMember(Name = "ResultCode")]
public string ResultCode { get; set; }
[DataMember(Name = "ResultDesc")]
public string ResultDesc { get; set; }
[DataMember(Name = "ThirdPartyTransID")]
public string ThirdPartyTransID { get; set; }
}
This is my deserializing code
M2PDto m2P = JsonConvert.DeserializeObject<M2PDto>(strResponse);
I can't seem to figure out how to deserialize it, keeps failing by passing null to m2P
this is my current code:
public string Get(int id)
{
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some URl that returns a json");
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
request.CachePolicy = noCachePolicy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return // RESPONSE AS JSON???;
}
public class Persons
{
public string index { get; set; }
public string thing { get; set; }
public string name { get; set; }
public string title { get; set; }
}
I want to return the response as multidimensional json..
How can i do that?
It should look like this:
{"data":{"Person1":{"id":1,"thing":"thingOne","name":"personOneName","title":"personOneTitle"},"Person2":{"id":2,"thing":"thingTwo","name":"personTwoName","title":"personTwoTitle"}}
Be sure to add the directive below to your class
using Newtonsoft.Json;
This code will turn your response into an object.
Stream newStream = response .GetResponseStream();
StreamReader sr = new StreamReader(newStream);
var result = sr.ReadToEnd();
//this will turn your response into a c# object of RootObject Type
//only do this is you're sure it will Deserialize into a RootObject type.
var convertResponseToObj= JsonConvert.DeserializeObject<RootObject>(result);
//if you want to see what's being returned by your endpoint
//without turning it into a RootObject type then remove <RootObject> see line below.
//doing this may help you Deserialize the response correctly.
//var convertResponseToObj= JsonConvert.DeserializeObject(result);
public class Persons
{
public string index { get; set; }
public string thing { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class RootObject
{
public List<Person> data {get; set;}
}
If you want to do some manipulations to that c# object and then turn it into JSON you can can do this:
string myJson = JsonConvert.SerializeObject(someCSharpObj); //this will turn your c# object into json
I have a WPF application that calls an API and creates an System.Xml.Linq.XDocument using XDocument.Parse(string). I am running into a problem where an XmlException ("Root element is missing") is thrown when I try to do this, but my XML is completely valid. I tried syntax-checking it by calling the API in my browser and checking its syntax, calling the API in my application and Console.WriteLineing the response, and using various XML syntax validators (all of which returned no errors).
A sample XML response from the API is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<event title="Event 1" id="75823347" icon="www.example.com/images/event1-icon.png" uri="www.example.com/rsvp/event1" mode="none" price="10.00" cover="www.example.com/event1-cover.png" enddate="2016-06-01 14:00:00" startdate="2016-06-01 12:00:00" address="1 Example St, Example City State 12345" location="Example Place" description="This is an event" shortdescription="This is an event" theme="auto" color="#FF000000"/>
</response>
This is my application's code:
public static WebRequest CreateRequest(string baseUrl, string httpMethod, Dictionary<string, string> requestValues) {
var requestItems = requestValues == null ? null : requestValues.Select(pair => string.Format("&{0}={1}", pair.Key, pair.Value));
var requestString = "";
if (requestItems != null)
foreach (var s in requestItems)
requestString += s;
var request = WebRequest.CreateHttp(baseUrl + CredentialRequestString + requestString);
request.Method = httpMethod.ToUpper();
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
return request;
}
public static WebRequest CreateRequest(string apiEndpoint, string endpointParam, int apiVersion, string httpMethod, Dictionary<string, string> requestValues) {
return CreateRequest(string.Format("http://www.example.com/api/v{0}/{1}/{2}", apiVersion, apiEndpoint, endpointParam), httpMethod, requestValues);
}
public static async Task<string> GetResponseFromServer(WebRequest request) {
string s;
using (var response = await request.GetResponseAsync()) {
using (var responseStream = response.GetResponseStream()) {
using (var streamReader = new StreamReader(responseStream)) {
s = streamReader.ReadToEnd();
}
}
}
return s;
}
public static async Task<List<Event>> GetEvents() {
var response = await GetResponseFromServer(CreateRequest("events", "", 1, "GET", null));
Console.WriteLine(response); //validation
var data = XDocument.Parse(response).Root; //XmlException: Root element is mising
return new List<Event>(data.Elements("event").Select(e => Event.FromXml(e.Value)));
}
Why is this happening?
The following code works
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
var data = XDocument.Load(FILENAME);
Event _event = Event.FromXml(data.Descendants("event").FirstOrDefault());
}
}
public class Event
{
public string title { get ; set; }
public string icon {get; set; }
public string uri { get; set; }
public string mode { get;set; }
public decimal price { get; set; }
public string cover { get; set; }
public DateTime enddate { get; set; }
public DateTime startdate { get; set; }
public string address { get; set; }
public string location { get; set; }
public string description { get; set; }
public string shortdescription { get; set; }
public string theme { get; set; }
public uint color { get; set; }
public static Event FromXml(XElement data)
{
Event _event = new Event();
_event.title = (string)data.Attribute("title");
_event.icon = (string)data.Attribute("icon");
_event.uri = (string)data.Attribute("uri");
_event.mode = (string)data.Attribute("mode");
_event.price = (decimal)data.Attribute("price");
_event.cover = (string)data.Attribute("cover");
_event.enddate = (DateTime)data.Attribute("enddate");
_event.startdate = (DateTime)data.Attribute("startdate");
_event.address = (string)data.Attribute("address");
_event.location = (string)data.Attribute("location");
_event.description = (string)data.Attribute("description");
_event.shortdescription = (string)data.Attribute("shortdescription");
_event.theme = (string)data.Attribute("theme");
_event.color = uint.Parse(data.Attribute("color").Value.Substring(1), System.Globalization.NumberStyles.HexNumber) ;
return _event;
}
}
}
My C# class
public class City
{
public int City_id { get; set; }
public string City_name { get; set; }
}
public class Model
{
public City[] lstCitiesResult { get; set; }
}
Web Request
string url = "my url";
WebRequest request = WebRequest.Create(url);
// provide your ID And Password for proxy
request.Proxy.Credentials = new NetworkCredential(XXXX);
WebResponse ws = request.GetResponse();
DataContractJsonSerializer jsonSerializer =
new DataContractJsonSerializer(typeof(List<Model>));
List<Model> dataList =
(List<Model>)jsonSerializer.ReadObject(ws.GetResponseStream());
string result = "";
foreach (var data1 in dataList)
{
result = result + data1.lstCitiesResult.ToString();
}
TextBox1.Text = result.ToString();
My error: I got null in datalist...what i do?