Httpclient.getasync() not working in windows 8 - c#

I am developing an app where I use the call httpclient.getasync(url).
This is working in UWP. Infact this code was working in windows 8 also.But when I tried today,It is giving weird exception(I didnot find anything in internet about this exception),Already spent lots of time.
Exception is Unable to cast object of type 'Windows.UI.Core.CoreDispatcher' to type 'System.Threading.IDispatcherQueue'
Here is my complete code.
public MainPage()
{
this.InitializeComponent();
getMarketList();
}
public async Task<string> GetUserPlayList(string url) // Get currents users all public playlists
{
try
{
HttpClient client = new HttpClient();
string url1 = url;
HttpResponseMessage response = await client.GetAsync(url1);
var res = response.Content;
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
return null;
}
}
private ObservableCollection<food> foodData = new ObservableCollection<food>();
public async Task getMarketList()
{
string url = "I have a valid url";
string format = await GetUserPlayList(url);
var data = JsonConvert.DeserializeObject<ApiCallResponse>(format);
foreach (var temp in data.result)
{
foodData.Add(temp);
}
}
Note-This was working earlier in windows 8 also and I am using preview builds of windows 10 and visual studio 2015

Related

Lead Ads Testing Tool - Server failure (102)

I'm trying to get Facebook leadgen ad data.
1-)As seen below, facebook sends the data to me successfully and I receive it successfully.
Successful Process img
2-)But the submissions I made on just this page do not come. What could be the reason for this?
Failed Process img
*But only the opinions I made on this page are not coming. What could be the reason for this?
Facebook doesn't even post. As seen in the picture, Server failure (102) information is displayed. What is the reason of this?
3-)The code I received the incoming data
Asp.Net Api Method
public async Task<HttpResponseMessage> Post([FromBody] JsonData data)
{
try
{
dbmanager db = new dbmanager();
db.Jsonkaydetv2(data);
var entry = data.Entry.FirstOrDefault();
var change = entry?.Changes.FirstOrDefault();
if (change == null) return new HttpResponseMessage(HttpStatusCode.BadRequest);
//Generate user access token here https://developers.facebook.com/tools/accesstoken/
const string token = "XXXX";
var leadUrl = $"https://graph.facebook.com/v2.10/{change.Value.LeadGenId}?access_token={token}";
var formUrl = $"https://graph.facebook.com/v2.10/{change.Value.FormId}?access_token={token}";
using (var httpClientLead = new HttpClient())
{
var response = await httpClientLead.GetStringAsync(formUrl);
if (!string.IsNullOrEmpty(response))
{
var jsonObjLead = JsonConvert.DeserializeObject<LeadFormData>(response);
db.JsonkaydetLeadFormData(jsonObjLead);
//jsonObjLead.Name contains the lead ad name
//Jsonkaydet(jsonObjLead.Name+"x");
//If response is valid get the field data
using (var httpClientFields = new HttpClient())
{
var responseFields = await httpClientFields.GetStringAsync(leadUrl);
if (!string.IsNullOrEmpty(responseFields))
{
var jsonObjFields =JsonConvert.DeserializeObject<LeadData(responseFields);
db.JsonkaydetLeadData(jsonObjFields);
//jsonObjFields.FieldData contains the field value
}
}
}
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception ex)
{
Jsonkaydet(ex.ToString());
Trace.WriteLine($"Error-->{ex.Message}");
Trace.WriteLine($"StackTrace-->{ex.StackTrace}");
return new HttpResponseMessage(HttpStatusCode.BadGateway);
}
}

Not working example for Dialogflow V2 api

Experienced problems with C# SDK documentation which can be found here:
http://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.Dialogflow.V2/api/Google.Cloud.Dialogflow.V2.SessionsClient.html#Google_Cloud_Dialogflow_V2_SessionsClient_Create_Google_Api_Gax_Grpc_ServiceEndpoint_Google_Cloud_Dialogflow_V2_SessionsSettings_
No reference for method ToChannelCredentials().
We cannot connect the SDK to dialogflow, even with blank project. Is this method still existing or deprecated?
using Google.Cloud.Dialogflow.V2;
using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
using Grpc.Core;
...
GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json");
Channel channel = new Channel(
SessionsClient.DefaultEndpoint.Host, SessionsClient.DefaultEndpoint.Port, cred.ToChannelCredentials());
SessionsClient client = SessionsClient.Create(channel);
...
// Shutdown the channel when it is no longer required.
channel.ShutdownAsync().Wait();
Have you tried connecting using the service account private key ? (Json file)
Follow these steps (working example in C#)
After you create a Dialogflow agent go to the agent's settings --> General --> click on the Service Account link
You will be sent to to google cloud platform where you can create a service account
After you create a service account, there will be an option to create a KEY, create it and download the (JSON) format of it
This key will be used to connect from your C# project to the Dialogflow agent
Install Google.Cloud.Dialogflow.V2 package in your project
Create for example a Dialogflow manager class (check below for an example)
public class DialogflowManager {
private string _userID;
private string _webRootPath;
private string _contentRootPath;
private string _projectId;
private SessionsClient _sessionsClient;
private SessionName _sessionName;
public DialogflowManager(string userID, string webRootPath, string contentRootPath, string projectId) {
_userID = userID;
_webRootPath = webRootPath;
_contentRootPath = contentRootPath;
_projectId = projectId;
SetEnvironmentVariable();
}
private void SetEnvironmentVariable() {
try {
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", _contentRootPath + "\\Keys\\{THE_DOWNLOADED_JSON_FILE_HERE}.json");
} catch (ArgumentNullException) {
throw;
} catch (ArgumentException) {
throw;
} catch (SecurityException) {
throw;
}
}
private async Task CreateSession() {
// Create client
_sessionsClient = await SessionsClient.CreateAsync();
// Initialize request argument(s)
_sessionName = new SessionName(_projectId, _userID);
}
public async Task < QueryResult > CheckIntent(string userInput, string LanguageCode = "en") {
await CreateSession();
QueryInput queryInput = new QueryInput();
var queryText = new TextInput();
queryText.Text = userInput;
queryText.LanguageCode = LanguageCode;
queryInput.Text = queryText;
// Make the request
DetectIntentResponse response = await _sessionsClient.DetectIntentAsync(_sessionName, queryInput);
return response.QueryResult;
}
}
And then this can be called like this for example to get detect Intents
DialogflowManager dialogflow = new DialogflowManager("{INSERT_USER_ID}",
_hostingEnvironment.WebRootPath,
_hostingEnvironment.ContentRootPath,
"{INSERT_AGENT_ID");
var dialogflowQueryResult = await dialogflow.CheckIntent("{INSERT_USER_INPUT}");

Continuous push message giving BadRequest from Azure

My service is register with azzure notification hub. And using my .net server API it push notification to particular device within particular time frame.
Everything goes right except when I try to send multiple push in same code it stuck with "BadRequest" except first one.
Below is the code
public static async void SendAzzurePushNotification()
{
for (int i = 0; i < 10; i++)
{
HttpStatusCode pushNotificationStatus = await CreateAndPushAsync("user_37");
Console.WriteLine(pushNotificationStatus);
}
}
static async Task<HttpStatusCode> CreateAndPushAsync(string tag)
{
HttpStatusCode pushNotificationStatus = HttpStatusCode.NotImplemented;
try
{
HttpResponseMessage response = null;
string uri = "<HUBURI>";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("SharedAccessSignature", <SASTOKEN>);
client.DefaultRequestHeaders.Add("ServiceBusNotification-Format", "gcm");
client.DefaultRequestHeaders.Add("ServiceBusNotification-Tags", tag);
client.DefaultRequestHeaders.Add("x-ms-version", "2015-01");
response = await client.PostAsync(uri,
new StringContent("{\"data\":{\"message\":\"Notification Hub test notification\"}}", Encoding.UTF8, "application/json"));
pushNotificationStatus = response.StatusCode;
}
catch (Exception ex)
{
throw;
}
return pushNotificationStatus;
}
Above code give me Created status for first time and then BadRequest after that. If same api I call from client like postman. It work fine.
I also tried nuget package from azure notification hub, regarding which code is as below. Which solve my above issue but it won't return me any status code which I can have in my above code for success.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<CONNECTIONSTRING>", "<HUB>");
NotificationOutcome outcome = await hub.SendGcmNativeNotificationAsync("{\"data\":{\"message\":\"Notification Hub test notification\"}}", "user_37");
Call send method with your tags and your notification-data
private static readonly string Endpoint = #"Your End Point";
private static readonly string HubName = #"You Hub Name";
private static NotificationHubClient Hub { get { return NotificationHubClient.CreateClientFromConnectionString(Endpoint, HubName); } }
public static async Task Send(string[] tags, object data)
{
try
{
string payload = string.Empty;
string json_gcm = string.Empty;
if (data.GetType() != typeof(string))
{
//If your notification data is of type
payload = JsonConvert.SerializeObject(data);
json_gcm = "{ \"data\" : " + payload + "}";
}
else
{
//If your notification data is simply is in string
payload = Convert.ToString(data);
json_gcm = "{ \"data\" : {\"message\":\"" + payload + "\"}}";
}
// Android
NotificationOutcome gcmOutcome = null;
gcmOutcome = await Hub.SendGcmNativeNotificationAsync(json_gcm, tags);
if (gcmOutcome != null)
{
if (!((gcmOutcome.State == NotificationOutcomeState.Abandoned) || (gcmOutcome.State == NotificationOutcomeState.Unknown)))
{
//Do code when notification successfully send to Android
}
}
}
catch (Exception ex)
{
//Do code when any exception occurred while sending notification
}
}
NotificationOutcomeState: Gives you status code in the form of enum that represent your notification has been successfully sent or not.
You may ignore if-else block as your need.
Try once may it help you

Trying to call public async Task<Boolean> from a public string submit method

I'm pretty new to this Async thing. I'm trying to write in to an API using a createasync method. However, for some reason I either get an aggregate exception, or the thread just hangs depending on what I've tried. Here is a code example because I have yet to be able to successfully write in to the Salesforce API. I have been able however, to pull back data using similar operations.
Submit Method where I want this all to take place in my controller:
[System.Web.Http.HttpPost]
public string Submit([FromBody]SurveyFormModel survey)
{
// todo - Validate data and stop if bad data comes in.
var report = BuildReport(survey.Questions);
try
{
var task = Task.Run(async () => { await SendReportToSalesforce(survey); });
task.Wait();
}
catch (Exception ex)
{
ex.GetBaseException();
}
EmailExcel(survey);
return JsonConvert.SerializeObject(report);
}
This is the method I'm using to call my salesforceservice.cs
public async Task SendReportToSalesforce([FromBody] SurveyFormModel survey)
{
SalesforceService service = new SalesforceService();
var auth = service.Authenticate();
var sfSurvey = service.SalesForceMapper(survey, survey.AccountDetails);
var result = await service.SendSurveytoSF(auth.Result, sfSurvey); //.Wait();
Console.WriteLine(result);
}
Also included is the salesforceservice class I use to authenticate as well as the method (SendSurveytoSF) that doesnt seem to be working.
public async Task<ForceClient> Authenticate()
{
//get credential values
var consumerkey = ConfigurationManager.AppSettings["consumerkey"];
var consumersecret = ConfigurationManager.AppSettings["consumersecret"];
var username = ConfigurationManager.AppSettings["username"];
var password = ConfigurationManager.AppSettings["password"];
//create auth client to retrieve token
var auth = new AuthenticationClient();
//get back URL and token
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
await
auth.UsernamePasswordAsync(consumerkey, consumersecret, username, password,
"https://test.salesforce.com/services/oauth2/token");
}
catch (Exception ex)
{
return null;
}
var instanceUrl = auth.InstanceUrl;
var accessToken = auth.AccessToken;
var apiVersion = auth.ApiVersion;
return new ForceClient(instanceUrl, accessToken, apiVersion);
}
public async Task<Boolean> SendSurveytoSF(ForceClient sfclient, Models.Salesforce.Survey survey)
{
survey.Account__c = "0012200000Ah3zG";
var response = await sfclient.CreateAsync("VBR_Assessment__c", survey);
return response.Id != null;
}
I believe I'm maybe just not calling these methods properly, but at this point I really have no clue as I've tried implementing it a ton of different ways. Thank you for any help in advanced!
UPDATE
This is the exception I'm getting:
A first chance exception of type 'Salesforce.Common.ForceException' occurred in mscorlib.dll

Windows store app C# Catch Error

I am developing a Windows store app, however I used this method to generate an user id when the app open by first time
private string host = "http://etc.com";
public async void RegisterUsuario() {
string displayName = await UserInformation.GetDisplayNameAsync();
string url = host + "/json/Register.php?code=" + displayName;
try
{
var http = new HttpClient();
var jsonText = await http.GetStringAsync(url);
var jsonValues = JsonArray.Parse(jsonText)[0];
var status = jsonValues.GetObject().GetNamedString("status");
if (status == "error")
{
var dialog = new MessageDialog("No se pudo registrar tu usuario", "¡Oops!");
await dialog.ShowAsync();
}
else
{
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values["usuario"] = jsonValues.GetObject().GetNamedNumber("id");
}
}
catch {
alertCatch("No se pudo registrar tu usuario");
}
}
THE JSON RESPONSE:
[{"status":"success","id":32}]
The problem:
In my pc always works fine, but when I submit the app to the windows store I always get this:
http://imgur.com/lOT09l7
the same error that will show the app in the CATCH.
Can you help me, maybe something in the appxmanifest?
In capabilities I selected private and public networks

Categories