Could not retrieve response from web service for xamarin forms - c#

Hi I am new to programming and I am still a student trying to learn C# and I am supposed to retrieve the response from the web service but I couldn't and it is unable to enter both the if and else statement. How do I resolve this error
.xaml.cs
private async void GetData(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://172.20.129.44/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//try
//{
HttpResponseMessage response = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
if (response.IsSuccessStatusCode)
{
string jsonString = await response.Content.ReadAsStringAsync();
dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
//string abc = dynamicObject["infoOpeningDays"].ToString();
// List<String[]> dynamicObject = JsonConvert.DeserializeObject<List<String[]>>(jsonString);
//Debug.WriteLine(dynamicObject[0].ToString());
//string abc = dynamicObject.IEnumerator.[0].IEnumerator.[0].IEnumerator.[0].IEnumerator.[5].Name;
try
{
// var abc = dynamicObject.GetType().GetProperty("infoOpeningDays").GetValue(dynamicObject);
String abc = (String)dynamicObject["infoOpeningDays"];
//JArray v = new JArray();
//v[0].data,tostring()
}
catch (Exception ex) { }
//Debug.WriteLine(abc.ToString());
// Debug.WriteLine((string)abc);
}
else
{
Debug.WriteLine("It entered else not if");
}
//}
//catch (Exception ex)
//{
// Debug.WriteLine(ex.ToString());
//}
}
.aspx
<Button Text="Get Data" TextColor="White" BackgroundColor="#4282bd" Clicked="GetData"/>
Web service
http://172.20.129.44/WebServices/information.svc/GetInformationJSON
Web service Data
{
"d": [
{
"__type": "Info:#website.Model",
"infoClosingDays": "Friday",
"infoClosingHours": "06:00:00 PM",
"infoID": 1,
"infoOpeningDays": "Monday",
"infoOpeningHours": "09:30:00 AM",
"infoStatus": "Open"
}
]
}
Someone Please Save me please

You can try using
HttpResponseMessage response = new HttpResponseMessage();
response.Content = client.GetAsync("WebServices/information.svc/GetInformationJSON").Result;
This might solve your issue.

Related

RestSharp v107 not returning data

I’ve used RestSharp 106 in the past but now I’m trying to get a new project up and running with v107. I did a simple test below but I can’t get it to return any data so I must be missing something that I’m not understanding. I’ve put a breakpoint at the top of the method and can follow it all the way down until it makes the async call and then the app just quits. I see the initial logging but again nothing after the async call. I would have thought I would see some logging about the list count or even the “Application END” piece. Anyone have any ideas on what I’m doing wrong? I’ve kept but commented out some of the different things I’ve tried.
Link to the documentation I’m looking at.
https://restsharp.dev/intro.html#introduction
public async void Run()
{
_log.LogInformation("Application START");
try
{
var listPPC = new List<PriorPeriodCorrection>();
listPPC = await CallApi();
}
catch (Exception ex)
{
_log.LogError("Error: {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
}
_log.LogInformation("Application END");
}
public async Task<List<PriorPeriodCorrection>> CallApi()
{
var listPPC = new List<PriorPeriodCorrection>();
var apiURL = "https://example.com";
var apiEndpoint = "api/payroll/getpriorpaycorrectiondata/from/2021-12-01/to/2021-12-07";
var proxyAddress = "http://example.com:9400";
var apiUsername = "someusername";
var apiPassword = "4PsaI69#tuv";
var options = new RestClientOptions(apiURL)
{
ThrowOnAnyError = true,
Timeout = 1000,
Proxy = new WebProxy(proxyAddress)
};
var client = new RestClient(options);
client.Authenticator = new HttpBasicAuthenticator(apiUsername, apiPassword);
var request = new RestRequest(apiEndpoint);
try
{
listPPC = await client.GetAsync<List<PriorPeriodCorrection>>(request);
//var response = await client.GetAsync<PriorPeriodCorrection>(request);
//var response = await client.GetAsync<List<PriorPeriodCorrection>>(request);
//var response = await client.GetAsync(request);
//if (!string.IsNullOrWhiteSpace(response.Content))
//{
// listPPC = JsonConvert.DeserializeObject<List<PriorPeriodCorrection>>(response.Content);
//}
//else
// _log.LogInformation("Response Content is Blank or NULL.");
}
catch (Exception ex)
{
_log.LogError("Error: {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
}
_log.LogInformation("Response count: {0}", listPPC.Count);
return listPPC;
}

Converting JSON to C#

I am trying to get a program I wrote in C# to post to a Slack channel through a Slack App but using formatting suggested here: https://api.slack.com/tools/block-kit-builder
I have this code below which posts to the Slack channel so I know that is working.
{
static void Main(string[] args)
{
PostWebHookAsync();
Console.ReadLine();
}
static async void PostWebHookAsync()
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "my-webhook-link"))
{
string jsonValue = JsonConvert.SerializeObject(new
{
type = "section",
text = "Some text \n new line \t tab",
}
);
Console.WriteLine(jsonValue);
Type valueType = jsonValue.GetType();
if (valueType.IsArray)
{
jsonValue = jsonValue.ToString();
Console.WriteLine("Array Found");
}
request.Content = new StringContent(jsonValue, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Content);
}
}
}
}
Which returns:
{"type":"section","text":"Some text \n new line \t tab"}
Now I want to POST this
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and <https://google.com|this is a link>"
}
}
But I am struggling to understand what to change this block of code for
string jsonValue = JsonConvert.SerializeObject(new
{
type = "section",
text = "Some text \n new line \t tab",
}
You need to do the following, the text property is an object, so just create another anonymous object.
string jsonValue = JsonConvert.SerializeObject(new
{
type = "section",
text = new
{
type = "mrkdwn",
text = "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and <https://google.com|this is a link>"
}
}

Exception in Json response when Submitting to webapi from WP8

I'm having issue when i try to send data to Web api which gives an exception
HRESULT E_FAIL has been returned from a call to a COM component
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState)
at response
HttpResponseMessage response = await client.GetAsync(String.Format(url, Isexist, jsontalleyHeader.ToString(), jsontalleydetail.ToString()));
Wp8 method
public async Task<string> POSTtalleyDetails(bool Isexist, int count)
{
string val = "";
if ((Isexist == false))//first time Load started--need headerNo
{
try
{
using (HttpClient client = new HttpClient())
{
var valjsontalleyHeader = listRtnTalleySheetHeader;
var jsontalleyHeader = Newtonsoft.Json.JsonConvert.SerializeObject(valjsontalleyHeader);
var valtalleydetail = listRtnTalleySheetDetail;
var jsontalleydetail = Newtonsoft.Json.JsonConvert.SerializeObject(valtalleydetail);
client.BaseAddress = new Uri("http://service:Port");
var url = "api/config/InsertTalleydetail?Isexist={0}&talleyheaderlist={1}&talleydetails={2}";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(String.Format(url, Isexist, jsontalleyHeader.ToString(), jsontalleydetail.ToString()));
if (response.IsSuccessStatusCode)
{
val = "Ok";
}
else
{
val = "No";
}
}
return val;
}
catch (Exception ex)
{
ex.ToString(); return val = "No";
}
//
}
}
where jsontalleydetail will be
[{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"39.0D39.053000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:53.7504239+05:30","_ConfirmedHatti":7,"_HattiId":1,"_HattiQty":5,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"40.0D40.053000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:53.8672939+05:30","_ConfirmedHatti":7,"_HattiId":2,"_HattiQty":1,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"41.0D41.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.0238698+05:30","_ConfirmedHatti":7,"_HattiId":3,"_HattiQty":2,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"42.0D42.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.1564773+05:30","_ConfirmedHatti":7,"_HattiId":4,"_HattiQty":5,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"43.0D43.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.2542986+05:30","_ConfirmedHatti":7,"_HattiId":5,"_HattiQty":2,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"44.0D44.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.3582527+05:30","_ConfirmedHatti":7,"_HattiId":6,"_HattiQty":1,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"45.0D45.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.4742785+05:30","_ConfirmedHatti":7,"_HattiId":7,"_HattiQty":2,"_HattiWeight":0}]
and
jsontalleyHeader will be
[{"_Remark":"","_TsStartTime":"2018-09-25T16:51:54.4742785+05:30","_TsEndDatetime":"0001-01-01T00:00:00","_VisitID":"VISIT0001783","_Approxweight":18.0,"_WHId":2,"_TalleySheetHeaderNo":"T2H1.033000","_Isedited":false,"_CreatedBy":null,"_visitID":null,"_Syncable":false,"_ID":null,"_ItemName":null,"_TalleySheetDetailNo":null,"_ItemMasterId":0,"_WareHouseId":0,"_ManufacturedDate":"0001-01-01T00:00:00","_LoadingTypeId":null,"_LoadingDate":"0001-01-01T00:00:00","_ConfirmedHatti":null,"_HattiId":null,"_HattiQty":null,"_HattiWeight":0}]
my web api method is
[HttpPost]
public HttpResponseMessage InsertTalleydetail([FromBody]List<clsTalleySheetHeader> talleyheaderlist, List<clsTalleySheetDetail>talleydetails)
{
return todoService.InsertTalleydetail(talleyheaderlist, talleydetails);
//base.BuildSuccessResult(HttpStatusCode.OK, StartTimeDetails);
}
I beleive this is because due to the data Load, because its work fine with 2 to 3 jsontalleydetail .
if could someone could advise me with regard to this , it will be a big help.
I was answered to similar question https://stackoverflow.com/questions/52202989/json-value-doesnt-assign-to-the-list-httppost

Fire TriggeredSends from ExactTarget's API using HttpClient REST

I've read along the way that Salesforce (I'm extremely new to this 3rd party platform) has a FUEL SDK which one can use instead of the version (using HttpClient -- REST instead of SOAP).
Please correct me if using FUEL SDK is the only way to go about requesting Salesforce's endpoints. Currently I am attempting to hit ExactTargets's API endpoints using HttpClient. These are the tutorials I've been basing my code off of:
https://developer.salesforce.com/docs/atlas.en-us.mc-apis.meta/mc-apis/messageDefinitionSends.htm
https://developer.salesforce.com/docs/atlas.en-us.mc-getting-started.meta/mc-getting-started/get-access-token.htm
Wanted Result:
To be able to request a Triggered Send email based off a template inside of ExactTarget.
Problem:
The Salesforce endpoint continuously returns a 404. I am able to receive the authorization token successfully. The GetAccessToken method is omitted for brevity
https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:MyExternalKey/send
I do not understand why the 2nd POST request to //www.exacttargetapis.com/..... returns a 404 but the authorization works. This leads me to believe that I do not have to use the FUEL SDK to accomplish triggering a welcome email.
Code:
private const string requestTokenUrl = "https://auth.exacttargetapis.com/v1/requestToken";
private const string messagingSendUrl = "https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends";
private string exactTargetClientId = ConfigurationManager.AppSettings["ExactTargetClientId"];
private string exactTargetClientSecret = ConfigurationManager.AppSettings["ExactTargetClientSecret"];
private string TriggerEmail(User model, string dbName)
{
var etExternalKeyAppSetting = ConfigurationManager.AppSettings.AllKeys.FirstOrDefault(x => x.Equals(dbName));
if (etExternalKeyAppSetting != null)
{
string etExternalKey = ConfigurationManager.AppSettings[etExternalKeyAppSetting];
HttpClient client = new HttpClient
{
BaseAddress = new Uri(string.Format(#"{0}/key:{1}/send", messagingSendUrl, etExternalKey)),
DefaultRequestHeaders =
{
Authorization = new AuthenticationHeaderValue("Bearer", this.GetAccessToken())
}
};
try
{
var postData = this.CreateExactTargetPostData(model.Email, etExternalKey);
var response = client.PostAsync(client.BaseAddress
, new StringContent(JsonConvert.SerializeObject(postData).ToString()
, Encoding.UTF8
, "application/json")).Result;
// get triggered email response
if (response.IsSuccessStatusCode)
{
dynamic result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
}
return "testing";
}
private object CreateExactTargetPostData(string email, string extKey)
{
var fromData = new
{
Address = ConfigurationManager.AppSettings["AwsSenderEmail"],
Name = "Test"
};
var subscriberAttributes = new { };
var contactAttributes = new
{
SubscriberAttributes = subscriberAttributes
};
var toData = new
{
Address = email,
//SubscriberKey = extKey,
//ContactAttributes = contactAttributes
};
var postData = new
{
From = fromData,
To = toData
};
return postData;
}
I have also tried using Advanced REST Client using the following:
URL:
https://www.exacttargetapis.com/messaging/v1/messageDefinitionSends/key:MyExternalKey/send
POST
Raw Headers:
Content-Type: application/json
Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Raw Payload:
{
"From": {
"Address": "code#exacttarget.com",
"Name": "Code#"
},
"To": {
"Address": "example#example.com",
"SubscriberKey": "example#example.com",
"ContactAttributes": {
"SubscriberAttributes": {
"Region": "West",
"City": "Indianapolis",
"State": "IN"
}
}
},
"OPTIONS": {
"RequestType": "ASYNC"
}
}
Issue was my App in the AppCenter was pointing to the incorrect login for MarketingCloud =(

How can web API take list and return different type for ASP.NET web API

I'm working in a project in which I want to add list<restaurant > in a web API method and return different types of mixed between restaurant and rest_location.
The relation between restaurant and rest_location is one to many.
When I run it, the error appears:
{"Message":"The requested resource does not support http method 'GET'."}
Server web API:
[HttpPost]
[Route("api/Restaurants/res_by_locat/{x}/{res_loc}")]
[ResponseType(typeof(Restaurant))]
[ResponseType(typeof(Rest_Location))]
public HttpResponseMessage GetResturantsBylocation([FromUri]int x,[FromBody] List<Rest_Location> res_loc)
{
List<Table> table = new List<Table>();
var lstitem = from t1 in res_loc
from t2 in db.Restaurants.Where(y => y.R_ID == t1.R_ID )
.DefaultIfEmpty()
select new { t1.L_Adress, t2.R_Name };
//foreach (var item in lstitem)
//{
// table.Add(item);
//}
if (lstitem == null || !lstitem.Any())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
else return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, new { lstitem });
}
Client:
protected void btn_ddl_Click(object sender, EventArgs e)
{
if (locationddl.SelectedValue == "0")
{
lbl_result.Text = "Chose a Location First ! ";
}
else
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:10566/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var fromddl = locationddl.SelectedItem.Text;
//lbl_result.Text = fromddl;
var response = client.GetAsync("api/Locations/getid_by_name/" + fromddl).Result;
// if (Page.IsValid)
{
if (response.IsSuccessStatusCode)
{
Location ll = response.Content.ReadAsAsync<Location>().Result;
int x = ll.L_ID;
lbl_msg.Text = x.ToString();
var response2_get_ids_Rests = client.GetAsync("api/Rest_Location/res_by_locat/" + x).Result;
if (response2_get_ids_Rests.IsSuccessStatusCode)
{
List<Rest_Location> rests_locations = response2_get_ids_Rests.Content.ReadAsAsync<List<Rest_Location>>().Result;
//var items= rests_locations.FirstOrDefault(rl => rl.L_ID == x);
// GridView2.DataSource = rests_locations;
// GridView2.DataBind();
HttpResponseMessage response3_get_resturants_by = client.PostAsJsonAsync("api/Restaurants/res_by_locat/" + x , rests_locations).Result;
if (response3_get_resturants_by.IsSuccessStatusCode)
{
var news= response3_get_resturants_by.Content.ReadAsAsync<List<Restaurant>>().Result;
GridView1.DataSource = news;
GridView1.DataBind();
lbl_msg.Text = "Search succesed";
}
else
{
lbl_test.Text = " not found ";
}
}
else
{
lbl_test.Text = " not found ";
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "Couldn't Found Resaurants ! " + ex.ToString();
}
}
}
You endpoint has this attribute, [HttpPost], implying that it can only be accessed using POST
Your client is attempting to access the endpoint using GET.
You should use client.PostAsync method instead of GetAsync.

Categories