Here Map Api using Retrofit Get Call - here-api

i am using ReveseGeocode Rest Api using Retrofit and the Call give me nothing
and using Route api to get distance between two points
always Call response give "'Package-Name'#someNumbers"`
private static Retrofit reGeoHereRetrofit =null;
public static Retrofit getReGeoHereRetrofit(){
if (reGeoHereRetrofit == null){
reGeoHereRetrofit = new Retrofit.Builder()
.baseUrl("https://reverse.geocoder.ls.hereapi.com/6.2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return reGeoHereRetrofit;
}
Interface.Class
public interface ReGeoHere {
#GET("reversegeocode.json")
public Call<ReGeoHereResponse> getReGeoAddress(#Query("prox") String LatLngD, #Query("mode") String
Mode, #Query("maxresults") String MaxResults, #Query("gen") String Gen, #Query("apiKey") String
MyApiKey, #Query("language") String Language);
}
and myclasses is getten using http://www.jsonschema2pojo.org for this json
{
"Response": {
"View": [
{
"Result": [
{
"Location": {
"Address": {
"Label": "S State St & W Madison St, Chicago, IL 60603, United States",
"Country": "USA",
"State": "IL",
"County": "Cook",
"City": "Chicago",
"District": "Loop",
"Street": "S State St & W Madison St"
}
}
}
]
}
]
}
}

Here is one of the examples:
curl
-X GET
-H 'Content-Type: *'
--get 'https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json'
--data-urlencode 'prox=41.8842,-87.6388,250'
--data-urlencode 'mode=retrieveAddresses'
--data-urlencode 'maxresults=1'
--data-urlencode 'gen=9'
--data-urlencode 'apiKey= '
https://developer.here.com/documentation/examples/rest/geocoder/reverse-geocode
It does return the response. Could you please double check your implementation?

Related

How to serialize json in newsofton on recurring datatable value in ASP.NET Core

So I've been trying to serialize a json that I have so that the defining value I get from my dataset is a "key" in my Json array and that all the values are within that key if that makes sense.
I'm new to this and I haven't found any other post that would help me with this so hopefully one of you knows the answer.
So the code that I'm using to try and achieve this is as following:
string query = #"
select Country.Name, City.Name from world.country
inner join world.city on world.country.Code = world.city.CountryCode
where CountryCode = #CountryCode";
DataSet dataSet = new DataSet("dataSet");
dataSet.Namespace = "NetFrameWork";
DataTable table = new DataTable();
dataSet.Tables.Add(table);
string sqlDataSource = _configuration.GetConnectionString("WorldAppConnection");
MySqlDataReader myReader;
using (MySqlConnection mySqlConnection = new MySqlConnection(sqlDataSource))
{
mySqlConnection.Open();
using (MySqlCommand mySqlCommand = new MySqlCommand(query, mySqlConnection))
{
mySqlCommand.Parameters.AddWithValue("#CountryCode", CountryCode);
myReader = mySqlCommand.ExecuteReader();
table.Load(myReader);
myReader.Close();
mySqlConnection.Close();
}
}
dataSet.AcceptChanges();
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
return json;
}
Now if I perform this query in SQL a small snippet of what the result is:
France | Paris
France | Marseille
France | Lyon
France | Toulouse
...
Now what this code results in as a Json is:
{
"Table1": [
{
"Name": "France",
"Name1": "Paris"
},
{
"Name": "France",
"Name1": "Marseille"
},
{
"Name": "France",
"Name1": "Lyon"
},
{
"Name": "France",
"Name1": "Toulouse"
},
{
"Name": "France",
"Name1": "Nice"
},
{
"Name": "France",
"Name1": "Nantes"
},
{
"Name": "France",
"Name1": "Strasbourg"
}
]
}
As you can see it keeps on repeating the France field. However the result I would want to have is something like:
{
"Table1": [
{
"France":[
{
"Name1": "Paris"
},
{
"Name1": "Marseille"
},
{
"Name1": "Lyon"
},
{
"Name1": "Toulouse"
},
{
"Name1": "Nice"
},
{
"Name1": "Nantes"
},
{
"Name1": "Strasbourg"
}
]
}
]
}
Is there any way to achieve this in any way?
Thanks in advance.
Before serialize the object, you can use LINQ to DataSet to group the result by the Name property, refer to the following sample code:
Create CountryViewModel class:
public class CountryViewModel
{
public string Name1 { get; set; }
}
Then use the following code (My application name is "Application1", you can change it to yours):
//group the country by the name,
var linqresult = dataSet.Tables[0].AsEnumerable()
.GroupBy(c => c.Field<string>("Name"))
.Select(c => new Dictionary<string, List<WebApplication1.Models.CountryViewModel>> {
{
(string)c.Key,
c.Select(i => new WebApplication1.Models.CountryViewModel() { Name1 = (string)i["Name1"] }).ToList()
}}).ToList();
var newdic = new Dictionary<string, List<Dictionary<string, List<WebApplication1.Models.CountryViewModel>>>>();
newdic.Add("Table1", linqresult);
var linqjson = JsonConvert.SerializeObject(newdic, Formatting.Indented);
The result is like this:
try this
dataSet.AcceptChanges();
//or this
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
var jsonParsed = JObject.Parse(json);
//or better
var jsonParsed = JObject.FromObject(dataSet);
var result = new
{
Table1 = jsonParsed["Table1"].GroupBy(x => x["Name"])
.Select(x => new Dictionary<string, string[]> { { (string)x.Key,
x.Select(i => (string)i["Name1"]).ToArray() }})
};
result
{
"Table1": [
{
"France": [
"Paris",
"Marseille",
"Lyon",
"Toulouse",
"Nice",
"Nantes",
"Strasbourg"
]
}
]
}

Ionic 3 & Woocommerce - retrieve/create customer using woocommerce customer api?

I'm completely new to woocommerce. I want to create a sign up page for shop app, so I'm trying to check if the email id entered by a customer while signing up is already exists or not, if not then create his account or else prompt the error "Email id already exists". I got the code from https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-customer but it is giving me an error while retrieving customer "No route was found matching the URL and request method".
here is my signup.ts code:
import * as WC from 'woocommerce-api';
WooCommerce: any;
newUser: any = {};
constructor()
{
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
wpAPI: true, // Enable the WP REST API integration
queryStringAuth: true,
verifySsl: true,
version: 'wc/v2' // WooCommerce WP REST API version
});
this.newUser.billing_address = {};
this.newUser.shipping_address = {};
}
checkEmail()
{
let validEmail = false;
let reg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if(reg.test(this.newUser.email))
{
this.WooCommerce.getAsync('customers/email/'+this.newUser.email)
.then((data) => {
let res = (JSON.parse(data.body));
console.log("data", res);
if(res.errors)
{
validEmail = true;
this.toastCtrl.create({
message: "Congratulations. Email is good to go!",
duration: 2000
}).present();
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Email already registered, please check.",
showCloseButton: true
}).present();
}
console.log(validEmail);
})
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Invalid Email. Please check.",
showCloseButton: true
}).present();
console.log(validEmail);
}
}
signup()
{
let customerData = {
customer : {}
}
customerData.customer = {
"email": this.newUser.email,
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"username": this.newUser.username,
"password": this.newUser.password,
"billing_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.billing_address.address_1,
"address_2": this.newUser.billing_address.address_2,
"city": this.newUser.billing_address.city,
"state": this.newUser.billing_address.state,
"postcode": this.newUser.billing_address.postcode,
"country": this.newUser.billing_address.country,
"email": this.newUser.email,
"phone": this.newUser.billing_address.phone,
},
"shipping_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.shipping_address.address_1,
"address_2": this.newUser.shipping_address.address_2,
"city": this.newUser.shipping_address.city,
"state": this.newUser.shipping_address.state,
"postcode": this.newUser.shipping_address.postcode,
"country": this.newUser.shipping_address.country
}
}
if(this.billing_shipping_same)
{
this.newUser.shipping_address = this.newUser.shipping_address;
}
this.WooCommerce.postAsync('customers',customerData).then((data) =>{
console.log(JSON.parse(data.body));
});
}
Error i'm getting while checking email:
I think you are the little bit confused with the WooCommerce REST API Route.
You trying this route /wp-json/wc/v2/customers/<id> and you are passing the id as customer email id. Correct?
This is not which where you can pass the id as customer email id. for id you have to pass the customer id.
Something like this /wp-json/wc/v2/customers/1
But if you are trying to get customer details by the email id then you can use this route.
/wp-json/wc/v2/customers?email=ajay#xyz.com
This route returns the data of the customer who are assigned with this email id ajay#xyz.com.
import * as WC from 'woocommerce-api';
WooCommerce: any;
newUser: any = {};
constructor()
{
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
wpAPI: true, // Enable the WP REST API integration
queryStringAuth: true,
verifySsl: true,
version: 'wc/v2' // WooCommerce WP REST API version
});
this.newUser.billing_address = {};
this.newUser.shipping_address = {};
}
checkEmail()
{
let validEmail = false;
let reg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if(reg.test(this.newUser.email))
{
this.WooCommerce.getAsync('customers?email='+this.newUser.email)
.then((data) => {
let res = (JSON.parse(data.body));
console.log("data", res);
if(res.errors)
{
validEmail = true;
this.toastCtrl.create({
message: "Congratulations. Email is good to go!",
duration: 2000
}).present();
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Email already registered, please check.",
showCloseButton: true
}).present();
}
console.log(validEmail);
})
}
else
{
validEmail = false;
this.toastCtrl.create({
message: "Invalid Email. Please check.",
showCloseButton: true
}).present();
console.log(validEmail);
}
}
signup()
{
let customerData = {
customer : {}
}
customerData.customer = {
"email": this.newUser.email,
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"username": this.newUser.username,
"password": this.newUser.password,
"billing_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.billing_address.address_1,
"address_2": this.newUser.billing_address.address_2,
"city": this.newUser.billing_address.city,
"state": this.newUser.billing_address.state,
"postcode": this.newUser.billing_address.postcode,
"country": this.newUser.billing_address.country,
"email": this.newUser.email,
"phone": this.newUser.billing_address.phone,
},
"shipping_address": {
"first_name": this.newUser.first_name,
"last_name": this.newUser.last_name,
"company": "",
"address_1": this.newUser.shipping_address.address_1,
"address_2": this.newUser.shipping_address.address_2,
"city": this.newUser.shipping_address.city,
"state": this.newUser.shipping_address.state,
"postcode": this.newUser.shipping_address.postcode,
"country": this.newUser.shipping_address.country
}
}
if(this.billing_shipping_same)
{
this.newUser.shipping_address = this.newUser.shipping_address;
}
this.WooCommerce.postAsync('customers',customerData).then((data) =>{
console.log(JSON.parse(data.body));
});
}
I have modified the route in your request you can check and let me know here i you are facing any issue.
try this
WooCommerceResult:any=[];
WooCommerce.getAsync('customers/email'+this.newUser.email).then((result) => {
console.log(result.toJSON().body);
this.WooCommerceResult=result.toJSON().body;
//return Promise.resolve(JSON.parse(result.toJSON().body));
// return JSON.parse(result.toJSON().body);
});
Bind WooCommerceResult in a view
remove extra parameters from this
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
wpAPI: true, // Enable the WP REST API integration
queryStringAuth: true,
verifySsl: true,
version: 'wc/v2' // WooCommerce WP REST API version
});
to::
this.WooCommerce = WC({
url: "http://localhost:1432/wordpress/",
consumerKey: "ck_*************************************",
consumerSecret: "cs_*************************************",
});

yammer integration :- writing activity using open_graph

While writing activity it return exception
ex {"The remote server returned an error: (400) Bad Request."}
I'm using the following code :-
public static string PostRequesttoYammer(string postBody, string url,string authHeader = null, string contentType = null)
{
string results = string.Empty;
try
{
HTTPWebReq = WebRequest.CreateHttp(url);
HTTPWebReq.Method = "POST";
if (!string.IsNullOrEmpty(authHeader))
HTTPWebReq.Headers.Add("Authorization: Bearer " + authHeader);
byte[] postByte = Encoding.UTF8.GetBytes(postBody);
if (string.IsNullOrEmpty(contentType))
HTTPWebReq.ContentType = "application/x-www-form-urlencoded";
else
HTTPWebReq.ContentType = contentType;
HTTPWebReq.ContentLength = postByte.Length;
Stream postStream = HTTPWebReq.GetRequestStream();
postStream.Write(postByte, 0, postByte.Length);
postStream.Close();
HTTPWebRes = (HttpWebResponse)HTTPWebReq.GetResponse();
postStream = HTTPWebRes.GetResponseStream();
StreamReader postReader = new StreamReader(postStream);
results = postReader.ReadToEnd();
postReader.Close();
postStream.Close();
}
catch (Exception ex)
{
}
return results;
}
I have obtained access token after that i'm trying to write an activity on yammer network .enter image description here
The image shows the content of local variables of function.
check the bellow code:
yam.platform.request({
url: "activity.json",
method: "GET",
data: {
"activity": {
"actor": { "name": "name", "email": "name#domain.onmicrosoft.com" },
"action": "create",
"object": {
"url": "https://www.news.google.com",
"image": "url",
"description": "Testing Description",
"title": "Open Graph Title"
},
"private": "false",
"message": "testing commit"
}
},
success: function (activity) {
console.log("Activity request was successful.");
},
error: function (activity) {
console.error("There was an error with the request.");
}
});

asp.net looping through json data error

I was using this example:
http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing
to test some dynamic JSON looping but I get an error that one of my data properties does not exist even though I see it in the data. Here is my JSON data:
[
{
"$id": "1",
"$type": "TheAPI.Models.Category, TheAPI",
"Id": 1,
"Name": "Marina Park",
"Description": "Morbi elementum diam sit amet mi viverra.",
"IsActive": true,
"NewsCategories": [
{
"$id": "2",
"$type": "TheAPI.Models.NewsCategory, TheAPI",
"Id": 1,
"NewsId": 2,
"CategoryId": 1,
"News": {
"$id": "3",
"$type": "TheAPI.Models.News, TheAPI",
"Id": 2,
"Headline": "Fake News Heading 2",
"ShortDesc": "A short description about the news item 2.",
"Body": "Mortgage loan rates may change daily. To ensure that you receive the rate you were quoted, you may elect to lock in your rate by paying an up-front authorization fee",
"CreateDate": "2014-07-04T00:00:00.000",
"PublishDate": "2014-07-04T00:00:00.000",
"ExpireDate": "2014-12-31T00:00:00.000",
"NewsCategories": [
{
"$ref": "2"
}
]
},
"Category": {
"$ref": "1"
}
},
{
"$id": "4",
"$type": "TheAPI.Models.NewsCategory, TheAPI",
"Id": 5,
"NewsId": 4,
"CategoryId": 1,
"News": {
"$id": "5",
"$type": "TheAPI.Models.News, TheAPI",
"Id": 4,
"Headline": "Fake News Heading 4",
"ShortDesc": "A short description about the news item 4.",
"Body": "Mortgage loan rates may change daily. To ensure that you receive the rate you were quoted, you may elect to lock in your rate by paying an up-front authorization fee",
"CreateDate": "2014-07-04T00:00:00.000",
"PublishDate": "2014-07-04T00:00:00.000",
"ExpireDate": "2014-12-31T00:00:00.000",
"NewsCategories": [
{
"$ref": "4"
}
]
},
"Category": {
"$ref": "1"
}
}
]
}
]
And here is my .Net code to consume it:
private void LoadNews()
{
//var url = apiurl + "/news";
var url = apiurl + "/categories?$filter=Id eq 1&$expand=NewsCategories/News";
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
//Response.Write(content);
JArray jsonVal = JArray.Parse(content) as JArray;
dynamic categories = jsonVal;
foreach (dynamic category in categories)
{
Response.Write("Cat Name: " + category.Name + "<br>");
foreach (dynamic newscat in category.NewsCategories)
{
foreach (dynamic news in newscat.News)
{
Response.Write(news.Headline + "<br>");
}
}
}
//ListView1.DataSource = categories.News;
//ListView1.DataBind();
}
When I run the above it seems like my news for each does not have all the data properties like the newscat and categories do. I get the following error:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'Headline'
Any help would be greatly appreciated. Thank you very much.
The News property on your NewsCategory isn't an array (just a single object). The .c# code below probably explains better than that...
foreach (dynamic category in categories)
{
Response.Write("Cat Name: " + category.Name + "<br>");
foreach (dynamic newscat in category.NewsCategories)
{
Response.Write(newscat.News.Headline + "<br>");
}
}

Malformed chunk in response

My simple controller:
class GeofencesController extends Controller
{
public function indexAction()
{
$json = '[
{
"id": 123,
"name": "muh",
"latitude": 32.121456,
"longitude": -19.238573,
"radius": 500
},
{
"id": 532,
"name": "blah",
"latitude": 32.121456,
"longitude": -19.238573,
"radius": 100
},
{
"id": 720,
"name": "bleh",
"latitude": 32.121456,
"longitude": -19.238573,
"radius": 200
}
]
';
$json = json_decode($json, true);
$response = new Response();
$response->setContent(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
is giving me a malformed chunked response. For example in java:
org.apache.http.MalformedChunkCodingException: Chunked stream ended unexpectedly
Chrome refuses to show the response, in Firefox i can see the response and Fiddler2 detects there is a Malformation with the response.
EDIT:
Also tried:
class GeofencesController extends Controller
{
public function indexAction()
{
$json = '[{"id": 123,"name": "bleh","latitude": 32.121456,"longitude": -19.238573,"radius": 500}]';
$json = json_decode($json, true);
$response = new JsonResponse($json);
return $response;
}
and still same problem. Is there a possibility this is related to Apache? Or Symfony2 config?
Try using JsonResponse object. I know it's supposed to be same" but I have seen some difference in Firefox...

Resources