I am trying to check if email is valid/invalid/unknown using GMASS API which sends "Status" as string value.
For example try these links:
Valid Email Response URL
Invalid Email Response URL
Retrieve "Status" value from JSON and set in Lable on Button click, How to achieve that?
What I tried, Inside button this code:
textBox.Text = "random#gmail.com";
HttpClient client1 = new HttpClient();
async Task Main1(string[] args)
{
string api = "https://verify.gmass.co/verify?email="+ textBox.Text + "&key=52D5D6DD-CD2B-4E5A-A76A-1667AEA3A6FC";
string response = await client1.GetStringAsync(api);
var status = JsonConvert.DeserializeObject<dynamic>(response);
label.Text = status.Status;
}
What went wrong with my code?
tested it in console app, was able to get status {invalid}
using (var client = new HttpClient())
{
string api = "https://verify.gmass.co/verify?email=" + textBox.Text + "&key=52D5D6DD-CD2B-4E5A-A76A-1667AEA3A6FC";
string response = client.GetStringAsync(api).Result;
var status = JsonConvert.DeserializeObject<dynamic>(response);
var x = status.Status;
}
for the async task you can do it like this
Note:It will take a little bit of time to get the result and update the label
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = await GetStatus(textBox1.Text);
}
public static async Task<string> GetStatus(string email)
{
using (var client = new HttpClient())
{
string api = "https://verify.gmass.co/verify?email=" + email + "&key=52D5D6DD-CD2B-4E5A-A76A-1667AEA3A6FC";
string response = await client.GetStringAsync(api);
var status = JsonConvert.DeserializeObject<dynamic>(response);
return status.Status;
}
}
Related
I dont get any response using client.PostAsync.
I created button in xamarin forms. It should send to server some sentences(json) and return info about them(again in json).
Button code:
private async void button_Analyze_Clicked(object sender, EventArgs e)
{
Request req = new Request()
{
UserId = this.UserId,
Language = Convert.ToString(picker_Language.SelectedItem) + ".",
Text = Convert.ToString(editor1.Text)
};
string jsonStr = JsonConvert.SerializeObject(req);
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("s", jsonStr);
FormUrlEncodedContent form = new FormUrlEncodedContent(dict);
HttpResponseMessage response = await client.PostAsync(markTextUrl, form).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
Answer answ = JsonConvert.DeserializeObject<Answer>(result);
answersList.Add(answ);
await DisplayAlert("", " ", "Ok");
}
Controller code:
public string MarkText(string s) //работа с запросом из приложения
{
Request req = JsonConvert.DeserializeObject<Request>(s);
if (req != null)
{
Models.Request request = new Models.Request()
{
Text = req.Text,
Lang = req.Language,
UserId = int.Parse(req.UserId)
};
AnalyzeRequest(request);
Answer answ = new Answer()
{
Language = req.Language,
Text = req.Text,
Sentences = db.Histories.Last().Text,
Labels = db.Histories.Last().Label
};
return JsonConvert.SerializeObject(answ);
}
return null;
}
Problem is this code
HttpResponseMessage response = await client.PostAsync(markTextUrl, form).ConfigureAwait(false);
never return response and it doesnt reach controller function. If I wait for this code to complete Ill get System.OperationCanceledExeption:"The operation was canceled"
I have an asp.net website which sends a tweet on a button click event.
I am using the TwitterApi for this and have an authenticated developer account.
This function was working from September 2018 until last month, but all of a sudden it won't send the tweets on request.
The response I get now is - "Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}""
After searching around, this doesn't seem like a twitter error, but an async error of some kind. I have made some minor alterations to my website in this time, but I cant see anything I have changed that would cause this issue.
The code is below.
Can any one see why this error would occur?
protected void Publish_Click(object sender, EventArgs e)
{
DataAccess.Publish();
SendEmails();
SendTweet();
Response.Redirect("OtherPage.aspx");
}
public static void SendTweet()
{
string text = DataAccess.GetText();
var twitter = new TwitterApi();
var response = twitter.Tweet(text);
}
public TwitterApi()
{
this.consumerKey = "XXX";
this.consumerKeySecret = "XXX";
this.accessToken = "XXX";
this.accessTokenSecret = "XXX";
sigHasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", consumerKeySecret, accessTokenSecret)));
}
public Task<string> Tweet(string text)
{
var data = new Dictionary<string, string> {
{ "status", text },
{ "trim_user", "1" }
};
return SendRequest("statuses/update.json", data);
}
Task<string> SendRequest(string url, Dictionary<string, string> data)
{
var fullUrl = TwitterApiBaseUrl + url;
// Timestamps are in seconds since 1/1/1970.
var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds);
// Add all the OAuth headers we'll need to use when constructing the hash.
data.Add("oauth_consumer_key", consumerKey);
data.Add("oauth_signature_method", "HMAC-SHA1");
data.Add("oauth_timestamp", timestamp.ToString());
data.Add("oauth_nonce", "a"); // Required, but Twitter doesn't appear to use it, so "a" will do.
data.Add("oauth_token", accessToken);
data.Add("oauth_version", "1.0");
// Generate the OAuth signature and add it to our payload.
data.Add("oauth_signature", GenerateSignature(fullUrl, data));
// Build the OAuth HTTP Header from the data.
string oAuthHeader = GenerateOAuthHeader(data);
// Build the form data (exclude OAuth stuff that's already in the header).
var formData = new FormUrlEncodedContent(data.Where(kvp => !kvp.Key.StartsWith("oauth_")));
return SendRequest(fullUrl, oAuthHeader, formData);
}
async Task<string> SendRequest(string fullUrl, string oAuthHeader, FormUrlEncodedContent formData)
{
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Add("Authorization", oAuthHeader);
var httpResp = await http.PostAsync(fullUrl, formData);
var respBody = httpResp.ToString();
return respBody;
}
}
I have a plugin using HttpClient which is supposed to create a record in external ERP database. I am sending a request, everything on my side is ok, I receive a status OK but response.Content.ReadAsStringAsync() is empty. In ERP database record is not created. Code below
public class OnPostCreate : BaseClass
{
private static Uri baseAdress = new Uri("http://adress/ws/Methodname.json?raw=");
private static HttpClient client = new HttpClient();
public static string trace = "";
public override void ExecutePlugin()
{
Account account = ((Entity)context.InputParameters["Target"]).ToEntity<Account>();
Account getAcc = dataContext.AccountSet.Where(p => p.Id == account.Id)
.Select(p => new Account()
{
Id = p.Id,
jar_id = p.jar_id,
jar_field1= p.jar_field1,
jar_field2= p.jar_field2,
jar_field3= p.jar_field3,
jar_field4= p.jar_field4
})
.SingleOrDefault();
if (getAcc == null) return;
ModelClass model = CreateModel(getAcc);
string content = GetContent(model);
Account acc = new Account
{
Description = baseAdress + content,
Id = getAcc.Id
};
service.Update(acc);
RunAsync(content, tracingService).GetAwaiter().GetResult();
tracingService.Trace(trace);
}
private static async Task RunAsync(string content, ITracingService tracingService)
{
client.BaseAddress = baseAdress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
try
{
await SendRequest(HttpMethod.Post, content);
}
catch (Exception e)
{
throw new InvalidPluginExecutionException(e.Message + e.InnerException + e.InnerException.InnerException);
}
}
private static async Task SendRequest(HttpMethod method, string query)
{
HttpRequestMessage request = new HttpRequestMessage(method, query);
HttpResponseMessage response = await client.SendAsync(request);
string responsetext = await response.Content.ReadAsStringAsync();
trace += "Code:" + response.StatusCode.ToString();
trace += "/n Response: " + responsetext;
response.EnsureSuccessStatusCode();
}
private ModelClass CreateModel(Account account) => new ModelClass()
{
Id = account.jar_id,
field4= account.jar_field4,
field1 = Convert.ToInt32(account.jar_field1 ),
field2= Convert.ToInt32(account.jar_field2),
field3= account.jar_field3
};
private string GetContent(ClassModel model) => $"<RequestData>" +
$"<Id>{model.Id}</Id>" +
$"<field1>{model.field1}</field1>" +
$"<field2>{model.field2}</field2>" +
$"<field3>{model.field3}</field3>" +
$"<field4>{model.field4}</field4>" +
$"</RequestData>";
}
Please help! Any suggestions why on my side everything seems to be OK (but response is empty??) and on the other side there is no even a mark of request.
I pasted the request url to postman and at first attempt i got no response, second one: 503 error Object reference not set to an instance of an object at DataService.Modules.Json.JsonHandler.Process(HttpListenerContext context) at DataService.Common.HttpServer.BeginGetContextCompleted(IAsyncResult result)
Regards
I'm trying to load data from https://www.quandl.com/api/v3/datatables/WIKI.
Comes out in a form like below
{"datatable":{"data":[["A","2017-11-14",66.98,67.8,66.89,67.46,1682158.0,0.0,1.0,66.98,67.8,66.89,67.46,1682158.0]],"columns":[{"name":"ticker","type":"String"},{"name":"date","type":"Date"},{"name":"open","type":"BigDecimal(34,12)"},{"name":"high","type":"BigDecimal(34,12)"},{"name":"low","type":"BigDecimal(34,12)"},{"name":"close","type":"BigDecimal(34,12)"},{"name":"volume","type":"BigDecimal(37,15)"},{"name":"ex-dividend","type":"BigDecimal(42,20)"},{"name":"split_ratio","type":"double"},{"name":"adj_open","type":"BigDecimal(50,28)"},{"name":"adj_high","type":"BigDecimal(50,28)"},{"name":"adj_low","type":"BigDecimal(50,28)"},{"name":"adj_close","type":"BigDecimal(50,28)"},{"name":"adj_volume","type":"double"}]},"meta":{"next_cursor_id":null}}.
However I try to load in asp .net like below but get an error saying it can't find data.
public partial class _Default : System.Web.UI.Page
{
protected string url = "https://www.quandl.com/api/v3/datatables/WIKI/PRICES?date=2017-11-14&ticker=A&api_key=<YOURAPIKEY>";
protected void Page_Load(object sender, EventArgs e)
{
//create an instance of HttpClient
HttpClient client = new HttpClient();
//DefaultRequestHeader to Json
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Create an instance of HttpResponse & invoke the service asynchronously
HttpResponseMessage response = client.GetAsync(url).Result;
//Http Status code 200
if (response.IsSuccessStatusCode)
{
//Read response content result into string variable
string JSON = response.Content.ReadAsStringAsync().Result;
//Deserialize the string(JSON) object
var jObj = (JObject)JsonConvert.DeserializeObject(JSON);
//access items from anonymous (Json object) type and add to the list
var result = jObj["datatable"].Select(item => new
{
key = item["data"][0],
code = item["data"][1],
description = item["data"][2],
buy = item["data"][3],
sell = item["data"][4],
}).ToList();
//output the data || NOTE: **NSERT into database table**
foreach (var item in result)
{
lblOutput.Text = item.key + "--" + item.code + "--" + item.description + item.buy + item.sell + "<br/>";
}
}
}
}
I can't seem to figure out how to load the data in the beginning bit of the json file
{"datatable":{"data":[["A","2017-11-14",66.98,67.8,66.89,67.46,1682158.0,0.0,1.0,66.98,67.8,66.89,67.46,1682158.0]],
You need to go over the data items not datatable items
var result = jObj["datatable"]["data"].Select(item => new
{
key = item[0],
code = item[1],
description = item[2],
buy = item[3],
sell = item[4],
}).ToList();
I have a unique issue, I want to get the name of an application from it's AppID while I convert an XML file into objects. This is the code I'm using at present:
if (xdoc.Element("Application") != null)
{
var data = from query in xdoc.Descendants("AppID")
select new APP
{
AppID = query.Value,
AppName = GetName(query.Value).ToString(),
};
itemGridView.DataContext = data;
}
This is the code I'm using to convert the GUID into an app name using Microsoft's Store API. I can confirm that it does return the app name. I'm just unsure how I can get this to display.
private async Task<string> GetName(string guid)
{
try
{
string link = "https://services.apps.microsoft.com/browse/6.2.9200-1/615/en-NZ_en-NZ/c/NZ/cp/10005001/Apps/{0}";
string url = string.Format(link, guid);
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
var response = await httpClient.SendAsync(httpRequestMessage);
var xmlString = await response.Content.ReadAsStringAsync();
XmlDocument NameXML = new XmlDocument();
NameXML = await XmlDocument.LoadFromUriAsync(new Uri(url));
string sAppName = NameXML.GetElementsByTagName("T")[0].ChildNodes[0].NodeValue.ToString();
return sAppName;
}
catch(Exception)
{
return guid;
}
}
I think my problem is with the async / await tasks. I've just been exposed to it now... how would I load up the App Name alongside the AppID when I parse the xml file?
The output that's being displayed when I run the app is "System.Threading.Tasks.Task[System.String]" (The objects load and the links and everything works fine, its just that the above is displayed instead of the app name).
I've been debugging using breakpoints, it appears that the GetName method only seems to be triggered later on, I'm not sure however.
Try to change this line :
AppName = GetName(query.Value).ToString(),
To this :
AppName = await GetName(query.Value),
GetName will return Task<string> instead of string when not awaited. And the method where above code resides required to be async because of using await inside that method :
private async void SomeMethod()
{
....
if (xdoc.Element("Application") != null)
{
var data = from query in xdoc.Descendants("AppID")
select new APP
{
AppID = query.Value,
AppName = await GetName(query.Value),
};
itemGridView.DataContext = data;
}
....
}
UPDATE :
As you already noticed, LINQ has very limited support for async/await currently. So to workaround this limitation, we can use normal for loop to avoid calling async function inside LINQ :
private async void SomeMethod()
{
....
if (xdoc.Element("Application") != null)
{
var query = from query in xdoc.Descendants("AppID")
select query.Value;
var data = new List<App>();
foreach (var q in query)
{
data.Add(new App{ AppId = q, AppName = await GetName(q) });
}
itemGridView.DataContext = data;
}
....
}