World Weather Online - Not able to retrieve information from <request> - c#

I am new to Windows Phone development, recently started to try to create a weather app, I am using API from World Weather Online (http://www.worldweatheronline.com/).
I retrieved the below sample data from the web site (http://free.worldweatheronline.com/feed/weather.ashx?q=paris&format=xml&num_of_days=5&key=xxxxxxxx):
<?xml version="1.0" encoding="UTF-8"?>
<data>
<request>
<type>City</type>
<query>Paris, France</query>
</request>
<current_condition>
.......
</current_condition>
<weather>
.......
</weather>
<weather>
.......
</weather>
</data>
I try to parse the xml and put them in a data class in C#. Below is my code:
XDocument doc = XDocument.Parse(e.Result);
var data1 = from q in doc.Descendants("result")
select new RequestData
{
type = (string)q.Element("type"),
query = (string)q.Element("query")
}
This is my data class:
public class RequestData
{
public string type {get; set;}
public string query {get; set;}
}
But after the above codes executed, there is no error (good), but there is no data from the data1.
I tried for doc.Descendants("current_condition) and doc.Descendants("weather") and I am able to get the data into the data1, only the doc.Descendants("result") didn't give me any result.
Anyone know why?
Thanks.

Ok, my bad, it's my own mistake, it should be "request", not "result".
It should be
doc.Descendants("request")
Not
doc.Descendants("result")

Related

Need help exporting data into a Term Base eXchange format

I need help exporting data into a xml Term Base eXchange format in a aspnet core application.
I am able to successfully export to UTF8 xml but I can't get any resource to help me export to a tbx format.
Thanks
This is my code:
[HttpGet]
public ContentResult ExtractTBX()
{
var movies = _context.Movie;
XmlSerializer serializer = new XmlSerializer(movies.GetType());
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, movies);
utf8 = writer.ToString();
}
return Content(utf8);
}
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
This is my output:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfMovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Movie>
<Id>1</Id>
<Title>When Harry Met Sally</Title>
<ReleaseDate>1989-02-12T00:00:00</ReleaseDate>
<Genre>Romantic Comedy</Genre>
<Price>7.99</Price>
<Rating>R</Rating>
</Movie>
...
</ArrayOfMovie>
This is my desired output:
<?xml version="1.0" encoding="UTF-8"?>
<martif type="TBX" xml:lang="en-US">
<martifHeader>
<fileDesc>
<titleStmt>
<title>CJO 116253 Net Software Engineer (gText)</title>
</titleStmt>
<sourceDesc>
<p>{Your Name}</p>
</sourceDesc>
</fileDesc>
</martifHeader>
<text>
<body>
<termEntry id="1">
<langSet xml:lang="en-US">
<descripGrp>
<descrip type="definition">{Genre}</descrip>
</descripGrp>
<ntig>
<termGrp>
<term id="6">Title</term>
<termNote type="partOfSpeech">{Rating}</termNote>
</termGrp>
</ntig>
</langSet>
</termEntry>
...
</body>
</text>
</martif>

Insert in DB a JSON object from a URL

I'm new to the REST API world. I explain my need: at a specific URL I have a raw JSON text, I would like this text to be acquired by my application and inserted later in the DB as a model I created previously through EF. C# NET-CORE 2.2.
if I wasn't clear enough, don't hesitate to ask me for more details.
Thanks in advance!
Edit:
I'm sorry if it' was unclear, I will provide more detail:
Actually, i have a JSON string downloaded from an url. I did it with the following code:
var client = new WebClient();
var jsonFull = client.DownloadString(string.Format("https://url"));
It's working fine. Now, I need to take from this string only a little part of the JSON, so i did:
using var jsonDoc = JsonDocument.Parse(jsonFull);
var jsonParsed = jsonDoc.RootElement;
var myCV = jsonParsed.GetProperty("cv");
CVE is an object of this JSON, and I succesfully take it.
Inside this object, there is another one called CV_data, so I extract this:
var myCVLE = myCV.GetProperty("CV_data_meta");
The result is a var with inside
ValueKind = Object : "{
"ID": "CV-2019",
"ASS": "cv#ms.org"
}"
Now, I have a class like that
public class CV_data_meta
{
[JsonPropertyName ("ID")]
public string ID { get; set; }
[JsonPropertyName("ASS")]
public string ASS { get; set; }
}
The question is: how i can put the value in the var myCVLE in the class CV_data_meta?
I tried with
var myCVClass = JsonSerializer.Deserialize<CV_data_meta>(myCVLE);
But I get an error.
Note: I can't deserialize all the string JSON into an object, because there are a lot of information that I don't need.
Thanks in advance all!
As I understand from your question, it follows:
You first need to create the JSON object mapping (class) that the API URL will return.
Then consume the API url like this:
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.yourapi.com/yourpath?yourkey={0}", yourkey));
receive and map object with mapped class
var yourvar = JsonConvert.DeserializeObject<yourclass>(reply);
Now you have the API return mapped to a class in your application, you can do whatever you want with it, including saving to a database.

How to change WebMethod XML output for ASP.NET Webservice, specifically namespace declaration?

I'm developing an ASP.NET Webservice (not WCF) for a given client. This is one of those situations, where you can not change anything at the client.
The client sends the following XML to request a method:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:cometxsd="http://werk-ii.de/soap/comet/Schema"
xmlns:comet="http://werk-ii.de/soap/comet"
xmlns:xop="http://www.w3.org/2004/08/xop/include"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:xmime5="http://www.w3.org/2005/05/xmlmime"
xmlns:ns1="http://soap.comet.werkii.com/">
<SOAP-ENV:Body>
<ns1:login xsi:type="ns1:login">
<user>myusername</user>
<password>mypassword</password>
<client>whatever</client>
<language>de</language>
</ns1:login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
My Service provides the login-Method like this:
[WebService(Namespace = "http://soap.comet.werkii.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class CometService : WebService
{
[WebMethod(MessageName = "login")]
[return: XmlElement("return")]
public LoginResult Login (string user, string password, string client, string language)
{
return new LoginResult() {
ResultCode = 0,
SessionId = user + "-" + password + "-" + client + "-" + language
};
}
}
public class LoginResult
{
[XmlElement("resultCode")]
public int ResultCode { get; set; }
[XmlElement("sessionId")]
public string SessionId { get; set; }
}
If I start the service, it tells me what SOAP 1.1 code I have to send as a request, that ist:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<login xmlns="http://soap.comet.werkii.com/">
<user>string</user>
<password>string</password>
<client>string</client>
<language>string</language>
</login>
</soap:Body>
</soap:Envelope>
When I use this code - as told by the service - from another test client (i wrote one in PHP), everything works fine an I get a result. But when I send the code from the beginning (which is what the real client will send), the method is called but all 4 arguments are null.
From an XML view, in my opinion both requests are the same. The only difference is, where the namespace is defined and if elements use the ns1 prefix. This should not make any difference, when the service reads it as XML. Maybe I'm wrong.
Perhaps the 4 arguments in the first XML have a different namespace (none) than the method (ns1). Can that be the reason why all arguments are null? How would I change the namespace for the arguments only?
When I change only the method lines in XML - replacing <ns1:login xsi:type="ns1:login"> with <login xmlns="http://soap.comet.werkii.com/"> and also the closing tag - it works! So the service seems not to understand my request, if the method element uses a namespace prefix, though the namespace is properly defined in the root element.
I tried the following to change the XML format which the service expects:
System.Web.Services.Protocols.SoapDocumentMethodAttribute - no effect at all
XmlNamespaceDeclarationsAttribute as shown here - which seems not to work because it is made for manipulating complex types, not the service class or a method
So the question is, how can I tell my service to accept the XML from the first example?
Good to know that parameters can also have Attributes:
public LoginResult Login (
[XmlElement(Namespace = "")] string user,
[XmlElement(Namespace = "")] string password,
[XmlElement(Namespace = "")] string client,
[XmlElement(Namespace = "")] string language)
{
return new LoginResult() {
ResultCode = 0,
SessionId = user + "-" + password + "-" + client + "-" + language
};
}
That's the solution to put the parameters into the global namespace – problem solved.

OpenSearch Autocomplete with ASP.net

My website currently adds a custom Omnibox search engine to chrome using the following code:
ombnibox.xml
<?xml version="1.0"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>Example </ShortName>
<Description>Example Search</Description>
<Url type="text/html" template="http://Example.com /search.aspx?searchVal= {searchTerms}"></Url>
</OpenSearchDescription>
My site master page includes:
<link type="application/opensearchdescription+xml" title="Example" rel="search" href="/omnibox.xml" />
This is working great and users are brought to my search results page without any issues. I would like to integrate search suggestions into this custom search engine but I don't even know where to start. I have found a bunch of PHP examples returning JSON but I cannot find an example for ASP.net or an example that retrieves the result suggestions from a database.
Any help would be awesome.
you need to add the following line to your xml file
<Url type="application/x-suggestions+json" method="get" template="http://www.domain.co.uk/autocomplete" />
and gets result in the following format:
["bm",["BMW","BMW X5","BMW X3","BMW 5 Series","BMW 1 Series","BMW 1 Series Cabriolet","BMW 3 Series","BMW Z4","BMW 3 Series Compact","BMW 116i"]]
Have a look at Mozilla's documentation
I hope this help you.
I looked into this more and I was able to create a web-service that returns properly formatted JSON values to be used by the Omnibox !!BUT!! the Omnibox code requires that a "GET" request is called to access the web-service which is blocked by ASP.net by default. Once I overwrote the default settings for ASP.NET to allow GET requests, it would only allow me to return XML formatted values.
I am currently under the assumption that using the Omnibox type-ahead feature isn't an option unless I create a non-ASP.net web-service.
UPDATE
I was able to figure this out using an ASP.NET MVC WebAPI and the following code:
public object Get(string id)
{
List<ResultObject> resultValues = new List<ResultObject>();
foreach (string val in ***SQLQUERYRESULTS***)
{
test singleResult = new ResultObject();
singleResult.Name = val;
singleResult.Description = "Server";
singleResult.Url = "***CUSTOMURL***?ServerName=" + val;
resultValues.Add(singleResult);
}
var entities = resultValues;
var names = entities.Select(m => m.Name);
var description = entities.Select(m => m.Description);
var urls = entities.Select(m => m.Url);
var entitiesJson = new object[] { id, names, description, urls };
return entitiesJson;
}
}
public class ResultObject
{
public string Name { get; set; }
public string Description { get; set; }
public string Url { get; set; }
}

Update Merchant Order ID in Amazon Marketplace

I need to update MerchantOrderID in Amazon Marketplace via Amazon MWS API using C#.
So, first I created XML file like:
<?xml version="1.0"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>M_STORE_3918753</MerchantIdentifier>
</Header>
<MessageType>OrderAcknowledgement</MessageType>
<Message>
<MessageID>1</MessageID>
<OrderAcknowledgement>
<AmazonOrderID>104-9209939-0469021</AmazonOrderID>
<MerchantOrderID>100828163</MerchantOrderID>
<StatusCode>Success</StatusCode>
<Item>
<AmazonOrderItemCode>11111111111111</AmazonOrderItemCode>
<MerchantOrderItemID>111111</MerchantOrderItemID>
<AmazonOrderItemCode>22222222222222</AmazonOrderItemCode>
<MerchantOrderItemID>222222222</MerchantOrderItemID>
</Item>
</OrderAcknowledgement>
</Message>
</AmazonEnvelope>
then I try to call Amazon MWS SubmitFeed:
SubmitFeedRequest request = new SubmitFeedRequest();
request.Merchant = merchantId;
request.MarketplaceIdList = new IdList();
request.MarketplaceIdList.Id = new List<string>(new string[] { marketplaceId });
request.FeedContent = File.Open(path, FileMode.Open, FileAccess.Read);
request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
request.FeedContent.Position = 0;
request.FeedType = "_POST_ORDER_ACKNOWLEDGEMENT_DATA_";
MarketplaceWebService.MarketplaceWebService serviceFeed = new MarketplaceWebServiceClient(
accessKeyId,
secretAccessKey,
applicationName,
applicationVersion,
configFeed);
SubmitFeedResponse response = serviceFeed.SubmitFeed(request);
it succesfully submits but when I open my order in Amazon (sellercentral.amazon.com) it says "none saved":
Your Merchant Order ID: # none saved
Who can help me, what is wrong or what should I do?
Thanks!
For those who want to update merchant order id in multiple orders at once, here is example (also works in amazon mws scratchpad):
<?xml version="1.0"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
<Header>
<DocumentVersion>1.01</DocumentVersion>
<MerchantIdentifier>ALVH0CYWPBFNA</MerchantIdentifier>
</Header>
<MessageType>OrderAcknowledgement</MessageType>
<Message>
<MessageID>1</MessageID>
<OrderAcknowledgement>
<AmazonOrderID>000-0000000-0000000</AmazonOrderID>
<MerchantOrderID>YOUR_MERCHANT_ORDER_ID</MerchantOrderID>
<StatusCode>Success</StatusCode>
</OrderAcknowledgement>
</Message>
<Message>
<MessageID>2</MessageID>
<OrderAcknowledgement>
<AmazonOrderID>000-0000000-0000000</AmazonOrderID>
<MerchantOrderID>YOUR_MERCHANT_ORDER_ID</MerchantOrderID>
<StatusCode>Success</StatusCode>
</OrderAcknowledgement>
</Message>
</AmazonEnvelope>
It's actually right code. Somehow amazon doesn't mark some special orders or marks them later.

Categories

Resources